diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts index 7310cc7c81ea0..5bd99a1ec44e2 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts @@ -346,13 +346,13 @@ export function makeCursorAgentSdkReplayRunner( new CursorReplayFrameMismatchError({ scenario: transcript.scenario, cursor, - expected: { type: "interaction.update | run.completed" }, + expected: { type: "interaction.update | run.retry | run.completed" }, actual: entry.frame, }), ); } const frame = entry.frame as CursorProtocolPayload; - if (frame.type === "interaction.update") { + if (frame.type === "interaction.update" || frame.type === "run.retry") { if (frame.runId !== runId) { return yield* recordFailure( new CursorReplayFrameMismatchError({ @@ -364,6 +364,7 @@ export function makeCursorAgentSdkReplayRunner( ); } advance(); + if (frame.type === "run.retry") continue; yield* (sendInput.onDelta?.(frame.update) ?? Effect.void).pipe( Effect.mapError((cause) => recordFailure( @@ -396,7 +397,7 @@ export function makeCursorAgentSdkReplayRunner( new CursorReplayFrameMismatchError({ scenario: transcript.scenario, cursor, - expected: { type: "interaction.update | run.completed" }, + expected: { type: "interaction.update | run.retry | run.completed" }, actual: frame, }), ); @@ -753,6 +754,14 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn( }; case "run.completed": return { ...frame, result: sanitizeReplayValue(frame.result, replacements) as RunResult }; + case "run.retry": + return { + ...frame, + diagnostic: sanitizeReplayValue( + frame.diagnostic, + replacements, + ) as typeof frame.diagnostic, + }; default: return frame; } diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts index 6521447763951..c8d2bfe99f7a9 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts @@ -26,6 +26,7 @@ import { makeCursorAgentSdkReplayRunner, } from "../Adapters/CursorAdapterV2.testkit.ts"; import * as CursorAdapterV2Testkit from "../Adapters/CursorAdapterV2.testkit.ts"; +import type * as CursorAgentSdk from "@t3tools/provider-cursor/server/CursorAgentSdk"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as EffectWorker from "../EffectWorker.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; @@ -151,16 +152,83 @@ const readClaudeCancelledSubagentResumeTranscript = Effect.fn( }); return yield* ClaudeOrchestratorReplayHarness.decodeTranscript({ ...recorded, entries }); }); -const readCursorTranscript = Effect.fn("readCursorRecoveryTranscript")(function* () { +const readCursorTranscript = Effect.fn("readCursorRecoveryTranscript")(function* ( + checkpointFailure: boolean, +) { const transcript = yield* readRawTranscript( new URL("./fixtures/provider_thread_resume/cursor_transcript.ndjson", import.meta.url), ); - return yield* CursorOrchestratorReplayHarness.decodeTranscript( + const recorded = yield* CursorOrchestratorReplayHarness.decodeTranscript( materializeReplayTranscriptRuntimeInstructions(transcript, { driver: ProviderDriverKind.make("cursor"), model: CURSOR_MODEL_SELECTION.model, }), ); + if (!checkpointFailure) return recorded; + let secondSession = false; + const oldAgent = String(recorded.metadata?.nativeAgentId); + const newAgent = "agent-after-checkpoint-failure"; + return yield* CursorOrchestratorReplayHarness.decodeTranscript({ + ...recorded, + entries: recorded.entries.flatMap( + (entry) => { + if (entry.type !== "emit_inbound" && entry.type !== "expect_outbound") return entry; + let frame = entry.frame as CursorAgentSdk.CursorAgentSdkProtocolLogEvent["payload"]; + if (entry.label === "run.completed:1" && frame.type === "run.completed") { + return [ + { + type: "emit_inbound", + label: "run.retry:1", + frame: { + type: "run.retry", + runId: frame.result.id, + diagnostic: { + requestId: frame.result.requestId, + originalRequestId: frame.result.requestId, + attempt: 0, + decision: "blocked_after_turn_ended", + turnEnded: true, + checkpoint: "none", + cause: { name: "Error", message: "Checkpoint persistence failed" }, + }, + }, + }, + { + ...entry, + frame: { + ...frame, + result: { + ...frame.result, + status: "error", + error: { + message: + "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session.", + }, + }, + }, + }, + ]; + } + if (frame.type === "agent.open" && frame.operation === "resume") { + secondSession = true; + const { agentId: _agentId, ...rest } = frame; + frame = { ...rest, operation: "create" }; + } + if (entry.label === "run.start:2" && frame.type === "run.start") { + frame = { + ...frame, + message: `Context handoff (full_thread_summary):\n\n\nUser message:\n${frame.message}`, + }; + } + return { + ...entry, + frame: secondSession + ? JSON.parse(JSON.stringify(frame).replaceAll(oldAgent, newAgent)) + : frame, + }; + }, + ), + }); }); function splitAfterFirstIdle(materialized: MaterializedOrchestratorFixtureInput) { @@ -182,6 +250,7 @@ function splitAfterFirstIdle(materialized: MaterializedOrchestratorFixtureInput) const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { readonly transcript: CursorAgentSdkReplayTranscript; readonly runner: ReturnType; + readonly checkpointFailure: boolean; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -211,16 +280,32 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ), }; + const sentMessages: string[] = []; + const runner: typeof input.runner = { + ...input.runner, + open: (openInput) => + input.runner.open(openInput).pipe( + Effect.map((session) => ({ + ...session, + send: (sendInput) => { + sentMessages.push( + typeof sendInput.message === "string" ? sendInput.message : sendInput.message.text, + ); + return session.send(sendInput); + }, + })), + ), + }; const harness = { ...CursorOrchestratorReplayHarness, makeProviderAdapterRegistryLayer: () => CursorAdapterV2Testkit.layer(input.transcript, { - runner: input.runner, + runner, assertCompleteOnFinalize: false, }), }; - yield* Effect.scoped( + const before = yield* Effect.scoped( runOrchestratorV2ProviderReplayScenario( { name: "provider_thread_resume/cursor:first-runtime", @@ -234,6 +319,11 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { options, ), ); + if (input.checkpointFailure) { + const first = projectionFor(before, input.transcript.scenario); + assert.equal(first.providerThreads[0]?.status, "error"); + assertAssistantTextIncludes(first, FIRST_FINAL); + } const result = yield* Effect.scoped( runOrchestratorV2ProviderReplayScenario( @@ -255,7 +345,7 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { result, transcript: input.transcript, runCount: 2, - runStatuses: ["completed", "completed"], + runStatuses: [input.checkpointFailure ? "failed" : "completed", "completed"], }); const projection = projectionFor(result, input.transcript.scenario); assertSemanticProjectionIntegrity(projection); @@ -269,6 +359,20 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { assertAssistantTextIncludes(projection, FIRST_FINAL); assertAssistantTextIncludes(projection, SECOND_FINAL); assert.lengthOf(projection.providerThreads, 1); + if (input.checkpointFailure) { + assert.include(sentMessages[1], "Context handoff (full_thread_summary):"); + assert.include(sentMessages[1], FIRST_FINAL); + assert.match( + sentMessages[1]!, + /\[Historical assistant;[^\]]+\]\nprovider thread resume fixture first turn complete/, + ); + assert.include(sentMessages[1], PROVIDER_THREAD_RESUME_SECOND_PROMPT); + assert.equal( + projection.providerThreads[0]?.nativeThreadRef?.nativeId, + "agent-after-checkpoint-failure", + ); + assert.equal(projection.contextHandoffs.at(-1)?.delivery?.status, "inline"); + } }); describe("orchestrator replay recovery", () => { @@ -370,14 +474,14 @@ describe("orchestrator replay recovery", () => { ), ); - it.effect( - "resumes a provider-native Cursor thread after recreating the orchestrator runtime", - () => + it.effect.each([false, true])( + "recovers a Cursor thread after recreating the orchestrator runtime (unconfirmed checkpoint: %s)", + (checkpointFailure) => Effect.scoped( Effect.gen(function* () { - const transcript = yield* readCursorTranscript(); + const transcript = yield* readCursorTranscript(checkpointFailure); const runner = makeCursorAgentSdkReplayRunner(transcript); - yield* runCursorRecovery({ transcript, runner }); + yield* runCursorRecovery({ transcript, runner, checkpointFailure }); yield* runner.assertComplete; }).pipe( provideDeterministicTestRuntime, diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json index b8e38d3b778cd..937e0e1c89478 100644 --- a/packages/provider-cursor/package.json +++ b/packages/provider-cursor/package.json @@ -49,7 +49,7 @@ "test": "vp test run --config ../../vite.config.ts --dir ." }, "dependencies": { - "@cursor/sdk": "1.2.0", + "@cursor/sdk": "1.3.1", "@napi-rs/keyring": "^1.3.0", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index 431b4489dfd78..cd6fc913155a8 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -6,6 +6,7 @@ import * as Layer from "effect/Layer"; import * as Exit from "effect/Exit"; import * as Cause from "effect/Cause"; import { vi } from "vite-plus/test"; +import * as NodeDiagnosticsChannel from "node:diagnostics_channel"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; @@ -136,6 +137,60 @@ const layerTest = CursorAgentSdk.layer.pipe( ); describe("CursorAgentSdkRunner", () => { + it.effect("logs an early retry failure under its run without recording request state", () => + Effect.gen(function* () { + const events: CursorAgentSdk.CursorAgentSdkProtocolLogEvent[] = []; + const retryCause = Object.assign(new Error("Checkpoint persistence failed"), { + cause: Object.assign(new Error("disk full"), { code: "ENOSPC" }), + request: { authorization: "must-not-be-logged", prompt: "private prompt" }, + }); + cursorSdkMock.send.mockImplementationOnce(async () => { + NodeDiagnosticsChannel.channel("s2code.cursor.retry").publish({ + requestId: "request-cursor-agent-sdk-test", + originalRequestId: "request-cursor-agent-sdk-test", + attempt: 0, + decision: "blocked_after_turn_ended", + turnEnded: true, + checkpoint: "none", + cause: retryCause, + }); + return { + id: "run-cursor-agent-sdk-test", + agentId: "agent-cursor-agent-sdk-test", + wait: cursorSdkMock.runWait, + cancel: cursorSdkMock.runCancel, + }; + }); + const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner( + () => (event) => + Effect.sync(() => { + events.push(event); + }), + ); + const session = yield* runner.open({ + operation: "create", + options: {}, + threadId: ThreadId.make("cursor-diagnostics"), + providerSessionId: ProviderSessionId.make("cursor-diagnostics"), + }); + const run = yield* session.send({ message: "hi" }); + yield* run.wait; + const retry = events.find((event) => event.payload.type === "run.retry"); + assert.equal(retry?.payload.type, "run.retry"); + if (retry?.payload.type !== "run.retry") return; + assert.equal(retry.payload.runId, "run-cursor-agent-sdk-test"); + assert.deepEqual(retry.payload.diagnostic.cause, { + name: "Error", + message: "Checkpoint persistence failed", + cause: { name: "Error", message: "disk full", code: "ENOSPC" }, + }); + assert.deepEqual( + events.map((event) => event.payload.type), + ["agent.open", "agent.opened", "run.start", "run.started", "run.retry", "run.completed"], + ); + }).pipe(Effect.provide(CursorSdk.layer)), + ); + it.effect("constructs without loading and reports first-use load failures as runner errors", () => Effect.gen(function* () { const failure = new Error("missing SDK chunk"); diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index f27ce65fa8e1e..0d184541aaa6d 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -19,6 +19,11 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as CursorSdk from "./CursorSdk.ts"; +import { + cursorRetryCause, + withCursorRetryDiagnostics, + type CursorRetryDiagnostic, +} from "./cursorRetry.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const; @@ -215,6 +220,17 @@ export type CursorAgentSdkProtocolLogEvent = readonly result: RunResult; }; } + | { + readonly direction: "incoming"; + readonly stage: "decoded"; + readonly payload: { + readonly type: "run.retry"; + readonly runId: string; + readonly diagnostic: Omit & { + readonly cause: ReturnType; + }; + }; + } | { readonly direction: "outgoing"; readonly stage: "decoded"; @@ -456,7 +472,7 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu }); let callbacksReady = false; - const pendingUpdates: Array = []; + const pendingCallbacks: Array<() => Promise> = []; let callbackFailure: { readonly cause: unknown } | undefined; let callbackChain = Promise.resolve(); let runId = ""; @@ -487,18 +503,48 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu const startRun = () => Effect.tryPromise({ try: () => - sendInput.summarize === true - ? agent.summarize() - : agent.send(sendInput.message, { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }), + withCursorRetryDiagnostics( + (diagnostic) => { + const dispatch = () => { + callbackChain = callbackChain + .then(() => + Effect.runPromiseWith(context)( + log({ + direction: "incoming", + stage: "decoded", + payload: { + type: "run.retry", + runId, + diagnostic: { + ...diagnostic, + cause: cursorRetryCause(diagnostic.cause), + }, + }, + }).pipe(Effect.ignore), + ), + ) + .catch((cause) => { + callbackFailure ??= { cause }; + }); + return callbackChain; + }; + if (!callbacksReady) pendingCallbacks.push(dispatch); + else void dispatch(); + }, + () => + sendInput.summarize === true + ? agent.summarize() + : agent.send(sendInput.message, { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingCallbacks.push(() => dispatchUpdate(update)); + return; + } + await dispatchUpdate(update); + }, + }), + ), catch: (cause) => runnerError(cause, "run.start"), }); const run = yield* startRun().pipe( @@ -542,9 +588,9 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu }, }); callbacksReady = true; - for (const update of pendingUpdates) { + for (const dispatch of pendingCallbacks) { yield* Effect.tryPromise({ - try: () => dispatchUpdate(update), + try: dispatch, catch: (cause) => runnerError(cause, "run.onDelta"), }); } diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 2e829860e0da2..6d311fba45156 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -376,6 +376,29 @@ describe("CursorAdapterV2", () => { }), failure: null, }, + { + reason: "an unconfirmed checkpoint after an answer without reusing the native session", + updates: [ + { type: "text-delta", text: "The answer." }, + { type: "turn-ended" }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + status: "error" as const, + error: { + message: + "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session.", + }, + }), + failure: { + class: "provider_error", + message: + "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session.", + retryable: false, + }, + threadDisposition: "broken" as const, + answers: ["The answer.", "The answer."], + }, { reason: "the error a continuation after the turn ended stopped with", updates: [ @@ -411,7 +434,7 @@ describe("CursorAdapterV2", () => { failure: null, answers: [], }, - ])("ends the turn with $reason", ({ updates = [], wait, failure, answers }) => + ])("ends the turn with $reason", ({ updates = [], wait, failure, answers, threadDisposition }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-failure-" }); @@ -511,6 +534,7 @@ describe("CursorAdapterV2", () => { assert.equal(terminal?.status, failure === null ? "completed" : "failed"); assert.equal(terminal?.failure?.class, failure?.class); assert.equal(terminal?.failure?.message, failure?.message); + assert.equal(terminal?.threadDisposition, threadDisposition ?? "reusable"); if (failure !== null) { assert.equal( terminal?.failure?.retryable, diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index bd5bf3d4dfe88..a4731dd2275a3 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -68,6 +68,7 @@ import { subagentThreadTitle, } from "@t3tools/provider-core/server/subagentProjection"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; +import { CURSOR_CHECKPOINT_UNCERTAIN_MESSAGE } from "./cursorRetry.ts"; import { isCursorSdkError } from "./sdk.ts"; export { cursorSdkModelSelection } from "./sdkModel.ts"; @@ -2529,12 +2530,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ); } if (context !== null) { + const checkpointUncertain = + result.error?.message === CURSOR_CHECKPOINT_UNCERTAIN_MESSAGE; const transportFailure = context.assistantReply.failure; const status = transportFailure === undefined ? terminalStatus(context, result) : "failed"; yield* finalizeTurn({ context, status, + ...(checkpointUncertain ? { threadDisposition: "broken" } : {}), ...(status === "failed" ? { failure: @@ -2544,6 +2548,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( // makeProviderFailure never reads a cause's own text. message: result.error?.message, ...usageLimitFailure(result.error, "provider_error"), + ...(checkpointUncertain ? { retryable: false } : {}), }) : makeProviderFailure({ cause: transportFailure, @@ -2659,6 +2664,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), resumeThread: Effect.fn("CursorAdapterV2.resumeThread")( function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { + if (threadInput.providerThread.status === "error") { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CursorAgentSdk.CURSOR_PROVIDER, + detail: CURSOR_CHECKPOINT_UNCERTAIN_MESSAGE, + }); + } const agentId = nativeThreadId(threadInput.providerThread); yield* openAgent({ operation: "resume", diff --git a/packages/provider-cursor/src/server/cursorRetry.test.ts b/packages/provider-cursor/src/server/cursorRetry.test.ts new file mode 100644 index 0000000000000..ef05e14743088 --- /dev/null +++ b/packages/provider-cursor/src/server/cursorRetry.test.ts @@ -0,0 +1,261 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Evaluates the installed SDK bundle in an isolated VM without starting a provider. +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodePath from "node:path"; +import * as NodeVM from "node:vm"; +import { describe, expect, it } from "vite-plus/test"; +import { withCursorRetryDiagnostics, type CursorRetryDiagnostic } from "./cursorRetry.ts"; + +const checkpointError = + "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session."; + +interface CheckpointHandler { + handleCheckpoint: ( + context: unknown, + state: unknown, + metadata?: { resumeEligibility: string }, + ) => Promise; + getLatestCheckpoint: () => unknown; +} + +interface Attempt { + attempt: number; + action: { action: { case: string } }; + checkpointHandler: CheckpointHandler; + notifyApplicationProgress: () => void; +} + +// The SDK bundles this private loop; execute the installed implementation with inert transport dependencies. +function loadRetryLoop(format: "cjs" | "esm") { + const require = NodeModule.createRequire(import.meta.url); + const directory = NodePath.dirname(require.resolve("@cursor/sdk")); + const source = NodeFS.readFileSync(NodePath.join(directory, "..", format, "305.js"), "utf8"); + const marker = source.indexOf( + "checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i", + ); + const start = source.lastIndexOf("async function ", marker); + const end = source.indexOf("new Set([", marker); + const loop = source.slice(start, end); + const name = /^async function (\w+)/.exec(loop)![1]!; + const initialDelay = /let c=(\w+);/.exec(loop)![1]!; + const uuid = /y=\(0,(\w+)\.C\)\(\)/.exec(loop)![1]!; + const proto = /g=new (\w+)\.QFf/.exec(loop)![1]!; + const sameState = /(\w+)\(\(x=m\)\.turns/.exec(loop)![1]!; + const errorClass = /error:new (\w+)\("Agent turn stopped/.exec(loop)![1]!; + const guardPath = NodePath.join(directory, "..", "s2code-retry.cjs"); + const globals = { + [initialDelay]: 0, + [uuid]: { C: () => "retry-request" }, + [proto]: { + QFf: function ConversationAction(input: object) { + return input; + }, + qKo: Object, + }, + [sameState]: () => true, + [errorClass]: Error, + s2codeRetryGuard: NodeFS.existsSync(guardPath) ? require(guardPath) : undefined, + }; + return NodeVM.runInNewContext(`${loop}; ${name}`, globals) as (input: object) => Promise; +} + +describe.each(["cjs", "esm"] as const)("Cursor SDK %s retry boundary", (format) => { + it.each([ + { + scenario: "original action", + checkpoint: false, + continuation: false, + terminal: false, + expectedAttempts: 1, + failure: true, + }, + { + scenario: "older resumable checkpoint", + checkpoint: true, + continuation: false, + terminal: false, + expectedAttempts: 1, + failure: true, + }, + { + scenario: "failed continuation after an answer", + checkpoint: true, + continuation: true, + terminal: false, + expectedAttempts: 1, + failure: true, + }, + { + scenario: "persisted terminal checkpoint", + checkpoint: true, + continuation: false, + terminal: true, + expectedAttempts: 1, + failure: false, + }, + { + scenario: "mid-turn reconnect", + checkpoint: true, + continuation: false, + terminal: false, + expectedAttempts: 2, + failure: false, + midTurn: true, + }, + { + scenario: "terminal checkpoint write failure", + checkpoint: true, + continuation: false, + terminal: true, + writeFailure: true, + expectedAttempts: 1, + failure: true, + }, + { + scenario: "user interruption after an answer", + checkpoint: false, + continuation: false, + terminal: false, + cancelled: true, + expectedAttempts: 1, + failure: true, + }, + ])("handles $scenario without repeating completed work", async (fixture) => { + const run = loadRetryLoop(format); + const actions: string[] = []; + const answers: string[] = []; + const diagnostics: CursorRetryDiagnostic[] = []; + let toolExecutions = 0; + const state = { turns: [], rootPromptMessagesJson: [] }; + const interaction = { + sendUpdate: async (_context: unknown, update: { message: { case: string } }) => { + if (update.message.case === "turnEnded") answers.push("answer"); + }, + }; + const input = { + ctx: { canceled: false, signal: new AbortController().signal }, + state, + action: { action: { case: "userMessageAction" } }, + requestId: "original-request", + runOptions: { enableAgentRetries: true }, + interaction, + checkpointError: (cause: unknown, requestId: string) => + Object.assign(new Error(checkpointError, { cause }), { + requestId, + kind: "NonRetriableError", + }), + checkpointHandler: { + handleCheckpoint: async ( + _context: unknown, + _state: unknown, + metadata: { resumeEligibility: string }, + ) => { + if ( + "writeFailure" in fixture && + fixture.writeFailure && + metadata.resumeEligibility === "ineligible_terminal_turn" + ) { + throw Object.assign(new Error("Checkpoint persistence failed"), { + code: "SQLITE_FULL", + }); + } + }, + getLatestCheckpoint: () => state, + }, + cancellation: { toCancelledError: () => new Error("cancelled") }, + hooks: { + classify: (error: unknown, info: { attempt: number }) => + "cancelled" in fixture && fixture.cancelled + ? { + action: "throw", + error: Object.assign(new Error("Request cancelled"), { kind: "CancelledError" }), + } + : info.attempt < 1 + ? { + action: "retry", + immediate: true, + countAsTransportError: true, + countAsServerError: false, + } + : { action: "throw", error }, + runAttempt: async (attempt: Attempt) => { + actions.push(attempt.action.action.case); + if (fixture.checkpoint) { + await attempt.checkpointHandler.handleCheckpoint({}, state, { + resumeEligibility: "eligible", + }); + } + attempt.notifyApplicationProgress(); + if ("midTurn" in fixture && fixture.midTurn && attempt.attempt === 0) { + throw new Error("ECONNRESET before the answer"); + } + toolExecutions++; + await interaction.sendUpdate({}, { message: { case: "turnEnded" } }); + if (fixture.terminal) { + await attempt.checkpointHandler.handleCheckpoint({}, state, { + resumeEligibility: "ineligible_terminal_turn", + }); + } + if (fixture.continuation) + await interaction.sendUpdate({}, { message: { case: "textDelta" } }); + if (attempt.attempt === 0) throw new Error("ECONNRESET after the answer"); + }, + }, + }; + const result = withCursorRetryDiagnostics( + (event) => diagnostics.push(event), + () => run(input), + ); + if (fixture.failure) + await expect(result).rejects.toThrow( + "cancelled" in fixture ? "Request cancelled" : checkpointError, + ); + else await result; + expect(actions).toHaveLength(fixture.expectedAttempts); + expect(toolExecutions).toBe(1); + expect(answers).toEqual(["answer"]); + if (fixture.expectedAttempts === 2) + expect(actions).toEqual(["userMessageAction", "resumeAction"]); + expect(diagnostics).toHaveLength(1); + expect(diagnostics[0]?.originalRequestId).toBe("original-request"); + expect(diagnostics[0]?.decision).toBe( + "cancelled" in fixture + ? "throw" + : fixture.failure + ? "blocked_after_turn_ended" + : fixture.terminal + ? "completed_from_checkpoint" + : "retry", + ); + if ("writeFailure" in fixture) { + expect(diagnostics[0]?.checkpoint).toBe("eligible"); + expect(diagnostics[0]?.cause).toMatchObject({ code: "SQLITE_FULL" }); + } + }); + + it("allows stop-hook continuations on the original connection", async () => { + const run = loadRetryLoop(format); + const updates: string[] = []; + const interaction = { + sendUpdate: async (_context: unknown, update: { message: { case: string } }) => { + updates.push(update.message.case); + }, + }; + await run({ + ctx: { canceled: false }, + requestId: "continuation", + runOptions: {}, + interaction, + checkpointHandler: {}, + cancellation: {}, + hooks: { + runAttempt: async () => { + for (const type of ["turnEnded", "toolCallStarted", "textDelta", "turnEnded"]) { + await interaction.sendUpdate({}, { message: { case: type } }); + } + }, + }, + }); + expect(updates).toEqual(["turnEnded", "toolCallStarted", "textDelta", "turnEnded"]); + }); +}); diff --git a/packages/provider-cursor/src/server/cursorRetry.ts b/packages/provider-cursor/src/server/cursorRetry.ts new file mode 100644 index 0000000000000..b1c591efceba1 --- /dev/null +++ b/packages/provider-cursor/src/server/cursorRetry.ts @@ -0,0 +1,57 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Bridges the SDK's internal retry callback to the owning run. +import * as NodeAsyncHooks from "node:async_hooks"; +import * as NodeDiagnosticsChannel from "node:diagnostics_channel"; +import * as Schema from "effect/Schema"; + +export const CURSOR_CHECKPOINT_UNCERTAIN_MESSAGE = + "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session."; + +const RetryDiagnostic = Schema.Struct({ + requestId: Schema.String, + originalRequestId: Schema.String, + attempt: Schema.Number, + decision: Schema.Literals([ + "retry", + "throw", + "blocked_after_turn_ended", + "completed_from_checkpoint", + ]), + turnEnded: Schema.Boolean, + checkpoint: Schema.String, + cause: Schema.Unknown, +}); + +export type CursorRetryDiagnostic = typeof RetryDiagnostic.Type; + +const diagnosticScope = new NodeAsyncHooks.AsyncLocalStorage< + (event: CursorRetryDiagnostic) => void +>(); +const isRetryDiagnostic = Schema.is(RetryDiagnostic); + +NodeDiagnosticsChannel.subscribe("s2code.cursor.retry", (event) => { + const receive = diagnosticScope.getStore(); + if (receive !== undefined && isRetryDiagnostic(event)) receive(event); +}); + +export function withCursorRetryDiagnostics( + receive: (event: CursorRetryDiagnostic) => void, + run: () => A, +): A { + return diagnosticScope.run(receive, run); +} + +export function cursorRetryCause(cause: unknown) { + const details = (error: unknown) => { + if (!(error instanceof Error)) return { name: typeof error }; + const code: unknown = Reflect.get(error, "code"); + return { + name: error.name.slice(0, 100), + message: error.message.slice(0, 2000), + ...(typeof code === "string" || typeof code === "number" ? { code } : {}), + }; + }; + return { + ...details(cause), + ...(cause instanceof Error && cause.cause !== undefined ? { cause: details(cause.cause) } : {}), + }; +} diff --git a/patches/@cursor__sdk@1.3.1.patch b/patches/@cursor__sdk@1.3.1.patch new file mode 100644 index 0000000000000..801667ffb9e67 --- /dev/null +++ b/patches/@cursor__sdk@1.3.1.patch @@ -0,0 +1,84 @@ +diff --git a/dist/cjs/305.js b/dist/cjs/305.js +index 662e62f1d483b1fd9208f2bea371917306d90bb2..ec84d59b852f1575aa4d09757a380570d8227efc 100644 +--- a/dist/cjs/305.js ++++ b/dist/cjs/305.js +@@ -1,4 +1,5 @@ +-exports.id=305,exports.ids=[305],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>$N});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../context/dist/otel.js"),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});class u{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,c.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{l(e)}}}function d(e){return e instanceof Error?e.message:String(e)}function h(e){return"Failed to read skill file: "+d(e)}function p(e){return"Invalid skill frontmatter: "+d(e)}function f(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const m=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function g(e){return e.toLocaleString("en-US")}var w=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const y=102400;function v(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function b({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>y?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=y;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 S(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function k(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$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(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=e.slice(r+1).trim(),c=S(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=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=S(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 _(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 C(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const E=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];var x=r("../context/dist/logger.js"),P=r("../metrics/dist/index.js"),I=r("../proto/dist/generated/agent/v1/exec_pb.js"),R=r("../utils/dist/writable-iterable.js");const T=/https?:\/\/\S+/gi,A=/[)"'<>,.;:\]}]$/;function $(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&A.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(T,$),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const O=(0,x.h)("SimpleControlledExecManager"),F=(0,P.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),N=(0,P.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),j=(0,P.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),L={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 U extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function B(e){return e instanceof U?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class W{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}),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 H{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 I.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class q{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t}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,R.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new I.$Y({message:{case:"heartbeat",value:new I.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new I.$Y({message:{case:"streamClose",value:new I.D9({id:t.id})}})),N.increment(r,1,{exec_case:o})}catch(e){if(e instanceof R.W2)return;j.increment(r,1,{exec_case:o}),await a.write(new I.$Y({message:{case:"throw",value:new I.Fu({id:t.id,error:e instanceof Error?D(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:B(e)})}}))}finally{const e=performance.now()-u;F.histogram(r,e,{exec_case:o}),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:L[s])??`No handler found for server message of type ${s}`;return O.error(e,i,{messageCase:s}),j.increment(e,1,{exec_case:o}),async function*(){yield new I.$Y({message:{case:"throw",value:new I.Fu({id:t.id,error:i})}}),yield new I.$Y({message:{case:"streamClose",value:new I.D9({id:t.id})}})}()}static fromResources(e,t){const r=new q(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}async function z(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}}var G=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},V=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 K=(0,x.h)("ExecutorResource"),J=(0,P.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class Z{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=G(n,(0,c.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,c.mJ)(s),a=i?new I.Kg(i):void 0,l=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new I.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await z(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)J.increment(s,1,{hook_event_name:t.hookEventName})}};p(d);let f=this.deserializeResult(d);for(;void 0===f;){const e=await z(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),f=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)p(e)}catch(e){K.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),f}catch(e){n.error=e,n.hasError=!0}finally{V(n)}}}class X{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=G(n,(0,c.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,c.mJ)(o),i=s?new I.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new I.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of a){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{V(n)}}}function Q(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function Y(e,t,r){return{name:e,symbol:Q(e),remoteImplementation:t,registerControlledImplementation:r}}class ee{constructor(e,t){this.resource=e,this.value=t}}function te(e,t){return[e,t]}function re(e,t){return t}class ne{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new ee(e,t))}get(e){return re(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class oe{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?re(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 se(e){return function(t,r){return new I.Ye({id:t,message:{case:e,value:r}})}}function ie(e){return t=>{if(t.message.case===e)return t.message.value}}function ae(e){return function(t,r){const n={case:e,value:r};return new I.yT({id:t,message:n})}}function ce(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const le=Y("agent-store-conflict-executor",(e=>new Z(e,se("agentStoreConflictArgs"),ie("agentStoreConflictResult"))),((e,t)=>{t.register(new W(e,ce("agentStoreConflictArgs"),ae("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class ue{async execute(e,t){return"ack"===t.op?{kind:"acked",count:0}:"release"===t.op?{kind:"released",count:0}:"noteDeferredEagerWrittenPaths"===t.op?{kind:"noted",count:0}:{kind:"not-applicable"}}}Y("agent-store-conflict-notice-executor",(e=>new ue),((e,t)=>{}));const de=Y("background-shell-executor",(e=>new Z(e,se("backgroundShellSpawnArgs"),ie("backgroundShellSpawnResult"))),((e,t)=>{t.register(new W(e,ce("backgroundShellSpawnArgs"),ae("backgroundShellSpawnResult")))})),he=Y("write-background-shell-input-executor",(e=>new Z(e,se("writeShellStdinArgs"),ie("writeShellStdinResult"))),((e,t)=>{t.register(new W(e,ce("writeShellStdinArgs"),ae("writeShellStdinResult")))}));function pe(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}const fe="local";function me(e,t){return`${e}:task_progress:${t}`}const ge=Y("canvas-diagnostics-executor",(e=>new Z(e,se("canvasDiagnosticsArgs"),ie("canvasDiagnosticsResult"))),((e,t)=>{t.register(new W(e,ce("canvasDiagnosticsArgs"),ae("canvasDiagnosticsResult")))}));Error;const we=Y("computer-use-executor",(e=>new Z(e,se("computerUseArgs"),ie("computerUseResult"))),((e,t)=>{t.register(new W(e,ce("computerUseArgs"),ae("computerUseResult")))})),ye=(Y("conversation-search-executor",(e=>new Z(e,se("conversationSearchArgs"),ie("conversationSearchResult"))),((e,t)=>{t.register(new W(e,ce("conversationSearchArgs"),ae("conversationSearchResult")))})),Y("delete-executor",(e=>new Z(e,se("deleteArgs"),ie("deleteResult"))),((e,t)=>{t.register(new W(e,ce("deleteArgs"),ae("deleteResult")))}))),ve=Y("diagnostics-executor",(e=>new Z(e,se("diagnosticsArgs"),ie("diagnosticsResult"))),((e,t)=>{t.register(new W(e,ce("diagnosticsArgs"),ae("diagnosticsResult")))}));var be=r("../context/dist/core.js");(0,be.cF)(Symbol("execConversationId"),void 0),(0,be.cF)(Symbol("execRequestId"),void 0),(0,be.cF)(Symbol("execBrowserOperationSource"),void 0);const Se=Y("fetch-executor",(e=>new Z(e,se("fetchArgs"),ie("fetchResult"))),((e,t)=>{t.register(new W(e,ce("fetchArgs"),ae("fetchResult")))})),ke=Y("git-diff-executor",(e=>new Z(e,se("gitDiffRequest"),ie("gitDiffResponse"))),((e,t)=>{t.register(new W(e,ce("gitDiffRequest"),ae("gitDiffResponse")))})),_e=Y("grep-executor",(e=>new Z(e,se("grepArgs"),ie("grepResult"))),((e,t)=>{t.register(new W(e,ce("grepArgs"),ae("grepResult")))})),Ce={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"},Ee={PreToolUse:Ce.preToolUse,PermissionRequest:null,PostToolUse:Ce.postToolUse,UserPromptSubmit:Ce.beforeSubmitPrompt,Stop:Ce.stop,SubagentStop:Ce.subagentStop,SessionStart:Ce.sessionStart,SessionEnd:Ce.sessionEnd,PreCompact:Ce.preCompact,Notification:null},xe=Object.fromEntries(Object.entries(Ee).filter((e=>Pe(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Pe(e){return Object.prototype.hasOwnProperty.call(Ee,e)}const Ie={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Re=["Glob"],Te=["Notification","PermissionRequest"],Ae=e=>"string"==typeof e,$e=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Me=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),De=(e,t=[])=>({isValid:e,errors:t});function Oe(e,t,r){void 0===e||Ae(e)||r.push(`${t} must be a string if provided`)}const Fe={warn:()=>{},info:()=>{}};function Ne(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?{type:"prompt",prompt:e.prompt,...r}:null:e.command?{type:"command",command:e.command,...r}:null}function je(e,t,r=Fe){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Fe){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=Ie[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Re.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=Ne(t,o);e&&n.push(e)}return n}function Le(e,t=Fe){const r={};for(const[n,o]of Object.entries(e)){if(!Pe(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Te.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Ee[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=je(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}}function Ue(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}const Be="Agent note: Do not suggest workarounds to the blocked tool.";function We(e){return e.includes(Be)?e:`${e}\n\n${Be}`}function He(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 qe(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)))}const ze=e=>{const t=[];return $e(e)?De(!0):(t.push("Expected an object"),De(!1,t))},Ge=e=>{const t=[],r=ze(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"),De(0===t.length,t)};function Ve(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 Ke=new Set([Ce.sessionStart,Ce.beforeSubmitPrompt,Ce.preToolUse,Ce.postToolUse,Ce.postToolUseFailure]);function Je(e){return"prompt"===e.type}function Ze(e){return"command"===e.type||void 0===e.type}const Xe={[Ce.beforeShellExecution]:Ge,[Ce.beforeMCPExecution]:Ge,[Ce.afterShellExecution]:e=>{const t=ze(e);return t.isValid,t},[Ce.afterMCPExecution]:e=>{const t=ze(e);return t.isValid,t},[Ce.beforeReadFile]:e=>{const t=[],r=ze(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"),De(0===t.length,t)},[Ce.afterFileEdit]:e=>{const t=ze(e);return t.isValid,t},[Ce.beforeTabFileRead]:e=>{const t=[],r=ze(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"),De(0===t.length,t)},[Ce.afterTabFileEdit]:e=>ze(e),[Ce.beforeSubmitPrompt]:e=>{const t=ze(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||Ae(e.additional_context)||r.push("additional_context must be a string if provided"),De(0===r.length,r)},[Ce.stop]:e=>{const t=ze(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"),De(0===r.length,r)},[Ce.afterAgentResponse]:e=>{const t=ze(e);return t.isValid,t},[Ce.afterAgentThought]:e=>{const t=ze(e);return t.isValid,t},[Ce.sessionStart]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if($e(e.env))for(const[t,n]of Object.entries(e.env))Ae(t)||r.push(`env key "${t}" must be a string`),Ae(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||Ae(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||Ae(e.user_message)||r.push("user_message must be a string if provided"),De(0===r.length,r)},[Ce.sessionEnd]:e=>{const t=ze(e);return t.isValid?De(!0,[]):t},[Ce.preCompact]:e=>{const t=ze(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return De(!0,[]);const r=[];if(!Me(e))return r.push("PreCompact response must be an object"),De(!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"),De(0===r.length,r)},[Ce.subagentStart]:e=>{const t=ze(e);if(!t.isValid)return t;if(!Me(e))return De(!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||Ae(n.user_message)||r.push("user_message must be a string if provided"),De(0===r.length,r)},[Ce.subagentStop]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];return Me(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),De(0===r.length,r)},[Ce.preToolUse]:e=>{const t=[],r=ze(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"),Oe(e.additional_context,"additional_context",t),De(0===t.length,t)},[Ce.postToolUse]:e=>{const t=[],r=ze(e);return r.isValid?(Oe(e.additional_context,"additional_context",t),De(0===t.length,t)):r},[Ce.postToolUseFailure]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];return Oe(e.additional_context,"additional_context",r),De(0===r.length,r)},[Ce.workspaceOpen]:e=>{const t=ze(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")),De(0===r.length,r)}},Qe=(e,t,r)=>{const n=function(e,t,r){let n;n=e===Ce.preToolUse?function(e,t){if(!lt(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(!ct(t))return r;const n=ut(e);if(!dt(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),lt(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Ce.stop?ht(t,r,"Stop"):e===Ce.subagentStop?ht(t,r,"SubagentStop"):t;const o=function(e,t,r,n){if(!Ke.has(e)||!lt(r)||void 0!==r.additional_context)return r;const o=lt(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!ct(r))return;const n=xe[e];if(void 0===n)return;const o=ut(t);return dt(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);return o}(e,t,r),o=(0,Xe[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Ye=[Ce.beforeShellExecution,Ce.beforeMCPExecution,Ce.beforeReadFile,Ce.beforeTabFileRead,Ce.subagentStart,Ce.preToolUse],et=[Ce.workspaceOpen];function tt(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 rt(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function nt(e){return Ye.includes(e)}function ot({step:e,command:t,failClosed:r,kind:n}){const o=nt(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:it(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function st(e,t){return t}function it(e,t){return nt(e)?st(0,{permission:"deny",user_message:t}):e===Ce.beforeSubmitPrompt||e===Ce.sessionStart?st(0,{continue:!1,user_message:t}):e===Ce.stop?st(0,{}):void 0}function at(e){try{return{value:JSON.parse(e)}}catch{return}}function ct(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function lt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ut(e){if(!lt(e))return;const t=e.hookSpecificOutput;return lt(t)?t:void 0}function dt(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function ht(e,t,r){if(!lt(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return{...n,followup_message:n.reason.trim()};if(!ct(t))return n;const o=ut(e),s=dt(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 pt=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function ft(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;e{const t=[];if(!$e(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)"),De(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Ae(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&&(Ae(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)=>{Ae(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(Ae(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),De(0===t.length,t)},kt=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),De(!1,r);for(let n=0;n{const t=[];if(!$e(e))return t.push("Hooks config must be an object"),De(!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"),!$e(e.hooks))return t.push("Config hooks must be an object"),De(!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(Ce),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=kt(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return De(0===t.length,t)};var Ct=r("../proto/dist/generated/agent/v1/hooks_pb.js");(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,be.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,be.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const Et=(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),xt=(0,be.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function Pt(e){return"inExecute"!==e.get(xt).kind}function It(e,t){const r=e.get(xt);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}const Rt=Y("hook-executor",(e=>new Z(e,se("executeHookArgs"),ie("executeHookResult"))),((e,t)=>{t.register(new W(e,ce("executeHookArgs"),ae("executeHookResult")))})),Tt=new Set(Object.values(Ce));function At(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function $t(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function Mt(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class Dt{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return Tt.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new I.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??"",...Ve(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(Ce.preCompact,t);return new I.S1({response:new I.w5({response:{case:"preCompact",value:new Ct.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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(Ce.subagentStart,t);return new I.S1({response:new I.w5({response:{case:"subagentStart",value:new Ct.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??"",...Ve(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:At(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(Ce.subagentStop,t);return new I.S1({response:new I.w5({response:{case:"subagentStop",value:new Ct.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Ce.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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 I.S1({response:new I.w5({response:{case:"beforeSubmitPrompt",value:new Ct.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Ce.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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 I.S1({response:new I.w5({response:{case:"afterAgentResponse",value:new Ct.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Ce.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new I.S1({response:new I.w5({response:{case:"afterAgentThought",value:new Ct.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Ce.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(e),status:At(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 I.S1({response:new I.w5({response:{case:"stop",value:new Ct.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(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(Ce.preToolUse,o);return new I.S1({response:new I.w5({response:{case:"preToolUse",value:new Ct.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(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(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(Ce.postToolUse,o);return new I.S1({response:new I.w5({response:{case:"postToolUse",value:new Ct.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:$t(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Ce.postToolUseFailure,o);return new I.S1({response:new I.w5({response:{case:"postToolUseFailure",value:new Ct.U1({additionalContext:s?.additional_context})}})})}default:return new I.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new I.S1({response:void 0})}}(0,be.cF)(Symbol("execHookConversationId"),void 0),(0,be.cF)(Symbol("execHookGenerationId"),void 0),(0,be.cF)(Symbol("execHookModel"),void 0);const Ot=(0,be.cF)(Symbol("execHookWorkspaceRoots"),void 0),Ft=Y("ls-executor",(e=>new Z(e,se("lsArgs"),ie("lsResult"))),((e,t)=>{t.register(new W(e,ce("lsArgs"),ae("lsResult")))})),Nt="cursor-ide-browser",jt="cursor-dev-control",Lt="custom-user-tools",Ut=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Nt,jt,Lt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Bt(e){return!Ut.has(e)}const Wt=new Set([jt,Nt]);function Ht(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function qt(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 zt;function Gt(e){return void 0===e||void 0===e.serverIdentifiers}function Vt(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,be.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"}(zt||(zt={}));const Kt=Y("mcp-executor",(e=>new Z(e,se("mcpArgs"),ie("mcpResult"))),((e,t)=>{t.register(new W(e,ce("mcpArgs"),ae("mcpResult")))})),Jt=Y("list-mcp-resources-executor",(e=>new Z(e,se("listMcpResourcesExecArgs"),ie("listMcpResourcesExecResult"))),((e,t)=>{t.register(new W(e,ce("listMcpResourcesExecArgs"),ae("listMcpResourcesExecResult")))})),Zt=Y("read-mcp-resource-executor",(e=>new Z(e,se("readMcpResourceExecArgs"),ie("readMcpResourceExecResult"))),((e,t)=>{t.register(new W(e,ce("readMcpResourceExecArgs"),ae("readMcpResourceExecResult")))})),Xt=Y("mcp-state-executor",(e=>new Z(e,se("mcpStateExecArgs"),ie("mcpStateExecResult"))),((e,t)=>{t.register(new W(e,ce("mcpStateExecArgs"),ae("mcpStateExecResult")))})),Qt=Y("mcp-allowlist-precheck-executor",(e=>new Z(e,se("mcpAllowlistPrecheckArgs"),ie("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("mcpAllowlistPrecheckArgs"),ae("mcpAllowlistPrecheckResult")))}));class Yt extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function er(e){if(e instanceof Yt)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}const tr=8388608;var rr=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),nr=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function or(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class ur{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 lr(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new nr.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const dr=Y("read-executor",(e=>new Z(e,se("readArgs"),ie("readResult"))),((e,t)=>{t.register(new W(e,ce("readArgs"),ae("readResult")))})),hr=Y("redacted-read-executor",(e=>new Z(e,se("redactedReadArgs"),ie("redactedReadResult"))),((e,t)=>{t.register(new W(e,ce("redactedReadArgs"),ae("redactedReadResult")))})),pr="$file:";const fr=(0,P.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),mr=(0,P.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),gr=(0,P.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"]}),wr=(0,P.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function yr(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${pr}${t}": ${r} A string argument of the form "${pr}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class vr extends Error{constructor(e){super(e.message),this.failure=e}}async function br(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=>(fr.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new rr.iz({result:{case:"error",value:new rr.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new vr(yr("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 a=r();if(void 0===a)throw new vr(yr("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,ir.xb)(t,(t=>async function(e,t,r,n,o,s){const i=await t.execute(e,new nr.a2({path:r,toolCallId:n,...s?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,n=s&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===n&&"content"!==t.output.case)throw new vr(yr("not_text",r,"the file is not a text file."));if(s&&(gr.increment(e,1,{source:void 0!==n?"vm_digest":"outdated_executor"}),void 0===n))throw new vr(yr("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."));const a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=n??await lr(a??"");if(t.truncated||l>o)throw new vr(yr("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${o} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return{content:a,bytes:l,sha256:c}}case"fileNotFound":throw new vr(yr("not_found",r,"the file does not exist."));case"permissionDenied":throw new vr(yr("permission_denied",r,"reading it was not permitted."));case"rejected":throw new vr(yr("rejected",r,`${i.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":throw new vr(yr("not_text",r,"the file cannot be read as text."));case"error":throw new vr(yr("read_error",r,i.result.value.error));default:throw new vr(yr("read_error",r,"the read returned no result."))}}(e,a,t,n,s,o)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new vr(yr("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 c}(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof vr?e.failure:yr("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(yr("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(pr))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,ar.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,fr.increment(e,1,{route:r,outcome:"expanded"}),mr.record(e,l,{route:r}),wr.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 Sr=/\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 kr(e,t,r,n){return Sr.test(t)?(fr.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${pr}/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 _r(e){return e.files.map((e=>`"${pr}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class Cr{constructor(e,t){this.inner=e,this.getReadExecutor=t}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 br(e,t,{route:"local",getReadExecutor:this.getReadExecutor});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=kr(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 rr._Z({content:{case:"text",value:new rr.zN({text:_r(r)})}})):"error"===n.result.case&&(n.result.value.error=kr(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const Er=Y("mini-swe-agent-bash-executor",(e=>new Z(e,se("miniSweAgentBashArgs"),ie("miniSweAgentBashResult"))),((e,t)=>{t.register(new W(e,ce("miniSweAgentBashArgs"),ae("miniSweAgentBashResult")))}));var xr=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Pr=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),Ir=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Rr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Tr=Y("shell-executor",(e=>new Z(e,se("shellArgs"),ie("shellResult"))),((e,t)=>{t.register(new W(e,ce("shellArgs"),ae("shellResult")))})),Ar=Y("shell-stream-executor",(e=>new X(e,se("shellStreamArgs"),ie("shellStream"))),((e,t)=>{t.register(new H(e,ce("shellStreamArgs"),ae("shellStream")))})),$r=((0,be.cF)(Symbol("optionalPendingPodWrite"),!1),Y("write-executor",(e=>new Z(e,se("writeArgs"),ie("writeResult"))),((e,t)=>{t.register(new W(e,ce("writeArgs"),ae("writeResult")))})));function Mr(e,t){return new Ir.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function Dr(e){return{execute:async(t,r)=>new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r.path,error:e,isReadonly:!0})}})}}function Or(e){return{execute:async(t,r)=>new Pr.Pi({result:{case:"permissionDenied",value:new Pr.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function Fr(e){return{execute:async(t,r)=>new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}const Nr=Y("record-screen-executor",(e=>new Z(e,se("recordScreenArgs"),ie("recordScreenResult"))),((e,t)=>{t.register(new W(e,ce("recordScreenArgs"),ae("recordScreenResult")))})),jr=Y("request-context-executor",(e=>new Z(e,se("requestContextArgs"),ie("requestContextResult"))),((e,t)=>{t.register(new W(e,ce("requestContextArgs"),ae("requestContextResult")))}));var Lr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const Ur=Y("shell-allowlist-precheck-executor",(e=>new Z(e,se("shellAllowlistPrecheckArgs"),ie("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("shellAllowlistPrecheckArgs"),ae("shellAllowlistPrecheckResult")))})),Br=Y("force-background-shell-executor",(e=>new Z(e,se("forceBackgroundShellArgs"),ie("forceBackgroundShellResult"))),((e,t)=>{t.register(new W(e,ce("forceBackgroundShellArgs"),ae("forceBackgroundShellResult")))}));function Wr(e,t){e.hookApprovalRequirement=void 0!==t?new Ir.In(t):void 0}function Hr(e){return e.hookApprovalRequirement}function qr(e){return e?.kind===Ir.b.FORCE_PROMPT}function zr(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&qr(e.hookApprovalRequirement))}Y("smart-mode-classifier-executor",(e=>new Z(e,se("smartModeClassifierArgs"),ie("smartModeClassifierResult"))),((e,t)=>{t.register(new W(e,ce("smartModeClassifierArgs"),ae("smartModeClassifierResult")))}));var Gr=r("../proto/dist/generated/agent/v1/agent_pb.js"),Vr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Kr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),Jr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Zr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Xr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Qr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Yr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class en 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 tn=e=>new Gr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Yr.lI({result:{case:"approved",value:new Yr.XJ}})}}),rn=(e,t)=>new Gr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Yr.lI({result:{case:"rejected",value:new Yr.yc({reason:t??""})}})}}),nn=e=>new Gr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Qr.fS({result:{case:"approved",value:new Qr.Hs}})}}),on=(e,t)=>new Gr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Qr.fS({result:{case:"rejected",value:new Qr.m$({reason:t??""})}})}}),sn=(e,t)=>new Gr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Gr.zT({result:t})}}),an=e=>new Gr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Xr.w$({result:{case:"approved",value:new Xr.q5}})}}),cn=(e,t)=>new Gr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Xr.w$({result:{case:"rejected",value:new Xr.rA({reason:t??""})}})}}),ln=(e,t)=>new Gr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Kr.gz({result:t})}}),un=(e,t)=>new Gr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),dn=(e,t)=>new Gr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),hn=(e,t)=>new Gr.Y5({id:e,result:{case:"prManagementResult",value:t}}),pn=(e,t)=>new Gr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Zr.h({result:{case:"rejected",value:new Zr.OI({reason:t??"Authentication was rejected"})}})}}),fn=(e,t)=>new Gr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new Vr.qG({result:{case:"rejected",value:new Vr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),mn=(e,t)=>new Gr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Jr.vW({result:{case:"approved",value:new Jr.l3({description:t??""})}})}}),gn=(e,t)=>new Gr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Jr.vW({result:{case:"rejected",value:new Jr.Uq({reason:t??""})}})}});var wn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),yn=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,be.cF)(Symbol("pendingSubagentReplay"),void 0);class vn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const bn=Y("subagent-executor",(e=>new Z(e,se("subagentArgs"),ie("subagentResult"))),((e,t)=>{t.register(new W(e,ce("subagentArgs"),ae("subagentResult")))})),Sn=Y("subagent-await-executor",(e=>new Z(e,se("subagentAwaitArgs"),ie("subagentAwaitResult"))),((e,t)=>{t.register(new W(e,ce("subagentAwaitArgs"),ae("subagentAwaitResult")))})),kn=Y("force-background-subagent-executor",(e=>new Z(e,se("forceBackgroundSubagentArgs"),ie("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new W(e,ce("forceBackgroundSubagentArgs"),ae("forceBackgroundSubagentResult")))}));class _n{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 Cn(e){return"string"==typeof e&&e.trim().length>0}const En=Y("web-fetch-allowlist-precheck-executor",(e=>new Z(e,se("webFetchAllowlistPrecheckArgs"),ie("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("webFetchAllowlistPrecheckArgs"),ae("webFetchAllowlistPrecheckResult")))})),xn=e=>e.replace(/[\r\n]/g,"");function Pn(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":xn(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":xn(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":xn(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const In="x-inference-authentication-jwt";function Rn(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[In]:t}}const Tn={textDelta:(e,t)=>new Gr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new Gr.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new Gr.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new Gr.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new Gr.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new Gr.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new Gr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new Gr.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new Gr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new Gr.tr3({thinkingDurationMs:e})}}),thinkingNote:e=>new Gr.Uq({message:{case:"thinkingNote",value:new Gr.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:Tn.toolCallDelta(e,new Gr.V1v({delta:{case:"taskToolCallDelta",value:new Gr.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new Gr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new Gr.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new Gr.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Gr.Uq({message:{case:"tokenDelta",value:new Gr.Fyz({tokens:e})}}),summary:e=>new Gr.Uq({message:{case:"summary",value:new Gr.ECk({summary:e})}}),summaryStarted:()=>new Gr.Uq({message:{case:"summaryStarted",value:new Gr.lWT}}),heartbeat:()=>new Gr.Uq({message:{case:"heartbeat",value:new Gr.ih1}}),summaryCompleted:(e,t,r)=>new Gr.Uq({message:{case:"summaryCompleted",value:new Gr.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new Gr.Uq({message:{case:"shellOutputDelta",value:new Gr.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new Gr.Uq({message:{case:"modelCallCompleted",value:new Gr.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 Gr.Uq({message:{case:"turnEnded",value:new Gr.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 Gr.QVp({rawCostCents:r,chargedCents:r,source:Gr.nnk.CATALOG})}:{}})}})},stepStarted:e=>new Gr.Uq({message:{case:"stepStarted",value:new Gr.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new Gr.Uq({message:{case:"toolRequestsListed",value:new Gr.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new Gr.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new Gr.Uq({message:{case:"stepCompleted",value:new Gr.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new Gr.Uq({message:{case:"activeBranchChange",value:new Gr.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new Gr.Uq({message:{case:"feedbackRequest",value:new Gr.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class An{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 $n=r("../agent-kv/dist/index.js");function Mn(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 Dn=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),On=r("../utils/dist/fresh-uuid.js"),Fn=r("@connectrpc/connect"),Nn=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),jn=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Ln=r("zod/v4");const Un="relayedAttemptFailure",Bn=Ln.object({transport:Ln.boolean(),stallAborted:Ln.boolean(),errorName:Ln.string(),connectCode:Ln.number().optional(),connectCodeName:Ln.string().optional(),connectCause:Ln.object({code:Ln.union([Ln.string(),Ln.number()]).optional(),name:Ln.string().optional()}).optional(),transportFailureKind:Ln.string().optional(),loop:Ln.string().optional(),transportMode:Ln.string().optional()});function Wn(e){const t=e?.details?.additionalInfo[Un];if(void 0!==t)try{const e=Bn.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class Hn 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 qn extends Hn{get kind(){return"RetriableError"}}class zn extends Hn{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Gn extends Hn{get kind(){return"NonRetriableError"}}class Vn extends Gn{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 Kn extends Hn{get kind(){return"CancelledError"}}const Jn=new Set([jn.yM.NOT_LOGGED_IN,jn.yM.AGENT_REQUIRES_LOGIN,jn.yM.AUTH_TOKEN_NOT_FOUND,jn.yM.AUTH_TOKEN_EXPIRED,jn.yM.INVALID_AUTH_ID,jn.yM.UNAUTHORIZED,jn.yM.GITHUB_NO_USER_CREDENTIALS,jn.yM.GITHUB_USER_NO_ACCESS]),Zn=new Set([jn.yM.FREE_USER_USAGE_LIMIT,jn.yM.FREE_USER_RATE_LIMIT_EXCEEDED,jn.yM.PRO_USER_ONLY,jn.yM.PRO_USER_USAGE_LIMIT,jn.yM.PRO_USER_RATE_LIMIT_EXCEEDED,jn.yM.RATE_LIMITED,jn.yM.RATE_LIMITED_CHANGEABLE,jn.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xn=new Set([jn.yM.USAGE_PRICING_REQUIRED,jn.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qn=new Set([jn.yM.BAD_API_KEY,jn.yM.BAD_USER_API_KEY,jn.yM.OUTDATED_CLIENT]),Yn=new Set([jn.yM.USER_ABORTED_REQUEST,jn.yM.DEBOUNCED]),eo=new Set([jn.yM.CUSTOM_MESSAGE]),to=new Map([[Fn.Code.PermissionDenied,"Permission Denied"]]),ro=["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"],no=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),oo=new RegExp(`\\b(${[...no].join("|")})\\b`),so=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],io="x-cursor-inference-request-error-type",ao="AgentWebSocketDeliveryAmbiguousError";function co(e,t={}){const{requestId:r}=t;if(e instanceof Hn)return e;if(lo(e))return function(e,t){const r=ho(e),n=r.code,o=po(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Un])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Un],t.details.equals(new jn.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:fo(r,io)??fo(e,io),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===Wn(o)?.transport?{isTransport:!0}:{}};if(n===Fn.Code.Canceled||n===Fn.Code.Aborted)return So(e)?new qn(e.message,a):new Kn(e.message,a);if(void 0!==s?.error){const t=s.error;if(Yn.has(t))return new Kn(yo(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new zn(yo(e,s),r,a);if(void 0!==Ro(s))return new qn(yo(e,s),a);if(Jn.has(t))return new zn(yo(e,s),"login",a);if(Zn.has(t))return new zn(yo(e,s),"upgrade",a);if(Xn.has(t))return new zn(yo(e,s),"payment",a);if(Qn.has(t))return new zn(yo(e,s),"config",a);if(eo.has(t)&&!0!==s.details?.isRetryable)return new Gn(yo(e,s),a);if(!1===s.details?.isRetryable)return new Gn(yo(e,s),a)}if(n===Fn.Code.Unauthenticated)return new zn(e.message,"login",{...a,displayInfo:uo(i,"Sign in required",r)});const c=to.get(n);return void 0===c||!0===s?.details?.isRetryable||So(e)?new qn(e.message,a):new Gn(yo(e,s),{...a,displayInfo:uo(i,c,r)})}(e,r);const n=(0,$n.y_)(e);if(void 0!==n)return new Gn(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===vo)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Gn(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 Gn(bo,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:bo,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Kn(e.message,{cause:e,requestId:r});if(e.name===ao)return new qn(e.message,{cause:e,requestId:r,isTransport:!0});if(So(e))return new qn(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qn(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lo(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 uo(e,t,r){return{...e,title:e.title||t,detail:e.detail||wo(r),isRetryable:e.isRetryable??!1}}function ho(e){let t=e;for(let e=0;e<10&&t.code===Fn.Code.Unknown;e++){const e=t.cause;if(!lo(e))break;t=e}return t}function po(e){let t=e;for(let e=0;e<10&&lo(t);e++){try{const e=t.findDetails?.(jn.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function fo(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 mo(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lo(t))return t;t="cause"in t?t.cause:void 0}}function go(e){const t=mo(e);return void 0===t?void 0:ho(t)}function wo(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function yo(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 vo="SummaryPlaceholderRejectedError",bo="Out of disk space. Free some space and try again.";function So(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(ro.some((t=>e.includes(t)))||oo.test(e))return!0;const n=r.code;if("string"==typeof n&&(ro.some((e=>n.includes(e)))||no.has(n)))return!0;r=r.cause}return!1}function ko(e){return ro.some((t=>e.includes(t)))||oo.test(e)}function _o(e){return e instanceof Hn&&e.cause instanceof Error?So(e.cause):e instanceof Error?So(e):"string"==typeof e&&ko(e)}function Co(e){return void 0!==e&&e>0}function Eo(e){return e+1}function xo(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Po(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Co(n)?xo(new qn("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Eo(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):xo(new qn("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}function Io(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(lo(t)&&(t.code===Fn.Code.Canceled||t.code===Fn.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Ro(e){const t=e?.details?.additionalInfo;if(e?.error!==jn.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 To=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},Ao=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 $o extends Error{constructor(e){super(e),this.name="LostConnection"}}class Mo{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{To(t,(0,c.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,ar.isMessage)(t,I.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const n=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,c.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,c.fU)(n)}else n=e;To(r,o?new c.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{Ao(r)}})();r.push(n)}await Promise.all(r)}catch(e){if(e instanceof Fn.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new $o(e.message);if(e instanceof Fn.ConnectError&&e.code===Fn.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 $o(e.message)}else{if(e instanceof R.W2)throw new $o(e.message);if(e instanceof Fn.ConnectError&&e.code===Fn.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new $o(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ao(t)}}}var Do=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Oo=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Fo=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),No=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class jo extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}jo.telemetryName="InteractionListenerStreamClosedError";var Lo=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 Uo=(0,x.h)("ClientInteractionController"),Bo=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Wo{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,c.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=>{Uo.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{Lo(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Bo.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 rn(e.id,t);case"webFetchRequestQuery":return on(e.id,t);case"askQuestionInteractionQuery":return sn(e.id,new Do.tz({result:{case:"rejected",value:new Do.ox({reason:t})}}));case"switchModeRequestQuery":return cn(e.id,t);case"createPlanRequestQuery":return ln(e.id,new Kr.bK({result:{case:"error",value:new Kr.iY({error:t})}}));case"setupVmEnvironmentArgs":return un(e.id,new No.r$({result:{case:"success",value:new No.JH({})}}));case"replaceEnvArgs":return dn(e.id,new Fo.dV({result:{case:"failure",value:new Fo.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return hn(e.id,new Oo.HL({result:{case:"error",value:new Oo.K$({error:t})}}));case"mcpAuthRequestQuery":return pn(e.id,t);case"connectScmRequestQuery":return fn(e.id,t);case"generateImageRequestQuery":return gn(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 Gr.Y5))throw r;return Uo.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=>{Uo.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ho(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Kn("User aborted request");throw new Gn("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Gn("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Gn("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new Gr.Ibo({bearerToken:r.bearerToken})}const qo=15728640,zo=(0,P.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Go=(0,P.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Vo=(0,P.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ko(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Jo{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,$n.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,$n.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,$n.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,$n.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,$n.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,ir.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 Zo({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ko(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(jr),o=await n.execute(e,new Lr._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),qo),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 Lr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Lr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Lr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Lr.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,$n.Bk)(i),(0,$n.Bk)(a),(0,$n.Bk)(c),(0,$n.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Lr.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,zo.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,zo.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 zo.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Go.histogram(e,m,{mode:o}),Vo.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 Xo(e){return Object.keys(e.fileContents).length>0}function Qo(e,t){return Object.assign(new(e.getType()),e,t)}function Yo(e){return Qo(e,{fileContents:{}})}function es(e){for(const[t]of e.entries())if(t.symbol===jr.symbol)return e.get(jr)}class ts{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function rs(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!==w.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=_(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)=>E.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(_);if(!i.some((e=>C(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&&!!(v(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>C(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 Lr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ns(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function os(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ns(r)&&ns(n)&&ns(o)&&ns(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,...ns(i)?{dynamicBytes:i}:{}}}const ss=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],is=/\bHTTP (\d{3})\b/;function as(e){const t=e.message;return"string"==typeof t?t:""}function cs(e){return e instanceof Error&&("AbortError"===e.name||e.name===ao)}const ls={serverCap:3,transportCap:10},us={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 ds(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function hs(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 Hn?e:co(e,{requestId:n});const c=a instanceof Kn&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Yn.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Kn||a instanceof qn),u="owner"===r.abortOrigin&&a instanceof qn&&Io(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(as),o=e=>n.some((t=>t.includes(e))),s=function(e){return go(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===Fn.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===Fn.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>is.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===Fn.Code.Unknown&&"464"===a?"http_464":i&&s===Fn.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===Fn.Code.DeadlineExceeded&&function(e){const t=mo(e);return void 0===t?void 0:po(t)?.error}(e)===jn.yM.TIMEOUT?"idle_deadline":i&&s===Fn.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":_o(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(cs)?"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(Po(f()),{countAsTransportError:!0});const e=p((()=>Po(f())),(()=>Po({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Kn&&!c&&Io(a)&&(a=new qn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Kn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof zn||a instanceof Gn)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!so.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):ds(d);if(a instanceof Kn||a instanceof zn||a instanceof Gn)return h(a);const m=function(e){return Ro(e.displayInfo?.errorDetails)}(a);if(a instanceof qn&&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}}return a instanceof qn&&(!0===a.isTransport||function(e,t){const r=us[e];return"by_signature"===r?_o(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Io(a))?p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Co(n)?new qn("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${Eo(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}}):new qn("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:"The connection was interrupted. Please check your network connection and try again.",isRetryable:!0,connectCode:o}})}(f())),(()=>a),{immediateFirstRetry:!0}):s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qn(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Eo(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):ds(d):h(a)}var ps=r("../proto/dist/generated/agent/v1/mcp_pb.js");const fs=(0,x.h)("@anysphere/agent-client:stall-detector"),ms=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,gs={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},ws=(0,P.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),ys=(0,P.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),vs=(0,P.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),bs=(0,P.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class Ss{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 ks{constructor(e,t,r){this.lastActivityTime=Date.now(),this.lastMeaningfulActivityTime=Date.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.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.logPrefix=gs[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),bs.increment(this.ctx,1,{loop:this.loop}),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}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=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.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=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=Date.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()}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{if(this.paused)return void(this.timer=setTimeout(e,this.thresholdMs));const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{if(this.paused)return void(this.advisoryTimer=setTimeout(t,e));const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{if(this.paused)return void(this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs));const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Ms),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName),this.abortedAt&&(r.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(r.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(r.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const n=[];let o;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:s}=this.activityHistory[e];o!==t&&(o?n.push(`[${t}]`):n.push(`[${t}] (MOST RECENT)`),o=t),n.push(`${r}${s?` (x${s})`:""}`)}return r.activities=n.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=Date.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=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Ms);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(fs.warn(this.ctx,a,i),ws.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",loop:this.loop}),this.hasEverStalled||(this.hasEverStalled=!0,vs.increment(this.ctx,1,{loop:this.loop})),this.onStallCallback){const t=Date.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:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs: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?.()}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});fs.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=Date.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),ys.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",loop:this.loop})}[Symbol.dispose](){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=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const _s=(0,be.cF)(Symbol("agentTransportTimingRecorder"),void 0),Cs=(0,x.h)("@anysphere/agent-client:turn-runner"),Es=1e3,xs=6e4;async function Ps(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Kn("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 Kn("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Is(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 Rs(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Ts(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let c=Es;const l=async(r,o,s,i,a)=>{if(s||(c=Es),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&&Cs.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Ps(n,o)}const l=s?function(e,t){const r=Math.min(3e5,3*e);return t??Es+(r-Es)*Math.random()}(c,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:Es,o=r??Math.min(n*2**e,xs);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,xs),n=Math.min(r+.2*r*Math.random(),xs);return Math.max(e,n)}(l,i.retryAfterMs);u!==l&&e.logging&&Cs.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:l,selectedDelayMs:u,endlessRetries:s}),s&&(c=l,e.logging&&Cs.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 Ps(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let u,d,h,p,f,m=e.state,g=e.action,w=0,y=o,v=0,b=0,S=!1,k=0;const _=()=>{S&&(n.onConnectionStateChange?.({state:"connected"}),S=!1)},C=e=>()=>{e===w&&(f=!0,_())},E=e=>({handleCheckpoint:async(t,n,o)=>{e===w&&(f=!0),await r.handleCheckpoint(t,n,o),e===w&&(u=n,d=o?.resumeEligibility??"eligible",_())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,y);if(u=void 0,d=void 0,f=!1,s.beginAttempt?.({attempt:w,originalRequestId:a}),w>0?(y=(0,On.C)(),await(n.onRetryStarting?.(w,{actionCase:g.action.case,conversationState:m,isResume:"resumeAction"===g.action.case,attemptRequestId:y})),e.logging&&Cs.info(t,`[${e.logging.tag}] Retrying attempt ${w}`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}),"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&Cs.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))):(e.logging&&Cs.info(t,`[${e.logging.tag}] Initial request`,{attempt:w,actionCase:g.action.case,requestId:y}),!0===e.notifyInitialResume&&"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&Cs.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,y);try{return await s.runAttempt({state:m,action:g,checkpointHandler:E(w),attempt:w,attemptRequestId:y,notifyConnected:_,notifyApplicationProgress:C(w)}),_(),void(e.logging&&Cs.info(t,`[${e.logging.tag}] Request successful`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,y);const o=!0===n.endlessRetries?.(),_=e.nowMs?.()??Date.now();f&&(h=void 0,p=void 0);const C=void 0===h?void 0:_-h,E=void 0===p?void 0:_-p;let I=s.classify(r,{attempt:w,attemptRequestId:y,originalRequestId:a,serverErrorRetries:v,transportErrorRetries:b,stallRetryElapsedMs:C,rateLimitRetryElapsedMs:E,endlessRetries:o});if("retry"===I.action){const n="resumeAction"===g.action.case||!0===e.noProgressGuardCountsReplays&&w>0;void 0!==u?k=0:n&&f&&(k++,k>=2&&(e.logging&&Cs.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:k,attempt:w,requestId:y,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),I={action:"throw",error:new qn("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:y,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:I.transportFailureKind}))}const R={...void 0===I.transportFailureKind?{}:{transportFailureKind:I.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},T=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===I.action?`RETRY (countAsServerError=${I.countAsServerError}, countAsTransportError=${I.countAsTransportError})`:`THROW ${I.error.kind}`;Cs.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${y} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===I.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:v,transportErrorRetries:b,attempt:w,requestId:y,originalRequestId:a,...R,...T})}if("throw"===I.action){if(0===w){const r={attempt:0,actionCase:g.action.case,error:I.error,requestId:y,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Cs.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:y,originalRequestId:a})}}throw e.logging&&Cs.warn(t,`[${e.logging.tag}] Error not retryable`,{...R,...T,attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a,errorName:I.error.name,...!0===e.logging.includeErrorObjects?{error:I.error}:{},serverErrorRetries:v,transportErrorRetries:b}),I.error}const A=w+1;if("ineligible_terminal_turn"===d)return void(e.logging&&Cs.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!==I.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:A,trigger:{...R,...s.reconnectTrigger?.(r,I,{originalRequestId:a,failedAttemptRequestId:y,nextAttempt:A})??{originatingRequestId:a,attemptRequestId:y}}}),S=!0),I.countAsServerError&&v++,I.countAsTransportError&&b++,!0===I.stall?h??=_:h=void 0,!0===I.rateLimit?p??=_:p=void 0,w=A,void 0!==u&&(P=u,Is((x=m).turns,P.turns)&&Is(x.rootPromptMessagesJson,P.rootPromptMessagesJson)||(c=Es),m=u,g=new Gr.QFf({action:{case:"resumeAction",value:new Gr.qKo}})),s.onRetryCommitted?.(),!0===I.immediate||!0===I.noBackoff&&void 0===I.retryAfterMs||await l(w,t.signal,o,I,r)}}var x,P}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var As=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},$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 Ms=(0,be.cF)(Symbol("agentStreamMetadata"),void 0),Ds=(0,x.h)("@anysphere/agent-client:abort"),Os=(0,x.h)("@anysphere/agent-client:retry"),Fs=(0,x.h)("@anysphere/agent-client:request-context-blob");async function Ns({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ko(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Xo(r)&&(t.requestContext=Yo(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Xo(o)&&(e.requestContextParts=Qo(n,{dynamicContext:Yo(o)}))}(t);try{const s=await Zo({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??qo,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?os(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?os(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fs.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 js=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 Ls(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 Us(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,Tn.shellOutputDelta({case:"stdout",value:new Ir.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,Tn.shellOutputDelta({case:"stderr",value:new Ir.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,Tn.shellOutputDelta({case:"exit",value:new Ir.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bs(e){return e instanceof Error?e.name:void 0}class Ws{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 Vn(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=es(e);return void 0===t?e:new oe(e,[te(jr,{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&&Xo(r)?new Lr._G({result:{case:"success",value:Qo(t,{requestContext:Yo(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new ts:void 0,y=void 0===w?g:function(e,t){const r=es(e);return void 0===r?e:new oe(e,[te(jr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?rs(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Jo(i),S=d.generationUUID??(0,On.C)(),k=new An,_=(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=mo(e);return void 0===t?void 0:Wn(po(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:Bs(e)},r=go(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=Bs(n);return{...t,underlyingConnectError:{code:r.code,codeName:Fn.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 I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Os.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=As(h,(0,c.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,c.MG)(R.span,(()=>Ts({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,...Rs(n)}}},cancellation:{toCancelledError:()=>new Kn("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})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Os.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Kn("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,d,y,b,a,o,u,v,i,S,k,C,c,l,s,I)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=hs(e,function(e,t,r=ls){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)&&ss.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 Hn?e:co(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{$s(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,d,h,p,f,m,g,w,y,v,b,S="agent.request.attempt"){const k={stack:[],error:void 0,hasError:!1};try{const E=e;e=this.options.prepareAttemptContext?.(e,{attempt:v,attemptRequestId:p,originalRequestId:f,runOptions:h})??e;const x=As(k,(0,c.VI)(e.withName(S)),!1);x.span.setAttribute("agent.attempt",v),x.span.setAttribute("agent.request_id",p),x.span.setAttribute("agent.original_request_id",f),e=x.ctx,e=(0,c.Mf)(e,"agent.request_id",p),e=(e=(0,c.Mf)(e,"agent.original_request_id",f)).with(Ms,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const P=new Set(g.sources);let T=void 0!==g.abortReasonName||void 0!==g.abortReasonMessage;const A=(t,r)=>{if(P.has(t))return;P.add(t),g.sources=[...P];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,g.abortReasonName=n.abortReasonName,g.abortReasonMessage=n.abortReasonMessage),Ds.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:p,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",Mn(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",Mn(t))}),{once:!0});const[$,M]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",Mn(e)),M()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",Mn(e)),M()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Kn("User aborted request")}const D=(0,c.VI)(e.withName("createControlledExecManager")),O=q.fromResources(s);D[Symbol.dispose]();const[F,N]=e.withCancel(),j=new Ss,{failThresholdMs:L,advisoryThresholdMs:U}=function(e,t){const r=ms(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=ms(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o{A("stall_detector",{thresholdMs:L,advisoryThresholdMs:U}),N()},onStallCallback:h.onStall,handlerTracker:j}),!1);let W,H;const z=(0,Nn.Jt)(),G=new R.F8(z,(e=>(B.reset("outbound_write",js(e)),e))),V=As(k,(0,c.VI)(e.withName("writeInitialRequest")),!1);let K;const J=function(e){return new ps.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(d),Z=h.requestContextBlobTransportMode??"legacy",X=0===v&&"userMessageAction"===r.action.case&&0===t.turns.length,Q="ref_only"===Z&&X?"dual":Z,[,Y]=await Promise.all([Ns({ctx:e,action:r,resources:s,blobStore:i,options:h,source:"run_request",transportMode:Q,notifyBytes:0===v}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):Ho(h.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:p})]),ee={action:r,headers:h.headers??{}},te=this.options.decorateAttempt?.(ee,h)??ee,re=new Gr.Mpn({conversationState:t,action:te.action,modelDetails:n,requestedModel:h.requestedModel,clientLlmGatewayCredential:Y,mcpTools:J,conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:h.subagentModelOverrides??[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,firstProjectOnboarding:h.firstProjectOnboarding,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,emitModelCallUsage:h.emitModelCallUsage,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,transcriptParentConversationId:h.transcriptParentConversationId,runId:f,nextInteractionQueryId:m.peekNext(),voiceCallNotes:h.voiceCallNotes});if(K=G.write(new Dn.KS({message:{case:"runRequest",value:re}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),V[Symbol.dispose](),new Kn("User aborted request")}const ne={...te.headers,"x-request-id":p,"x-original-request-id":f,...Pn(h),...Rn()};W=(0,c.VI)(e.withName("handshakeEstablishment")),W.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=function(e){return e?.get(_s)}(e)?.startTransportRun(),se=void 0===oe?W.ctx:function(e,t){return e.with(_s,t)}(W.ctx,oe),ie=0===v&&void 0!==h.onTtftBreakdown?b?.networkPhaseStartedAt:void 0;let ae;const ce=void 0===oe&&void 0===ie?z:(_=z,C=()=>{ae=performance.now(),oe?.markFirstRequestSent(ae)},{[Symbol.asyncIterator](){const e=_[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,C()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),le=this.client.run(se,ce,{signal:F.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===H&&(H=performance.now())}}),ue=performance.now();let de;const he=e=>{W&&(W.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==H&&W.span.setAttribute("handshake.preNetworkMs",H-ue),W[Symbol.dispose](),W=void 0),w();const t=performance.now();de=t,h.onFirstMessage?.(t-ue),void 0!==H&&h.onFirstMessageNetwork?.(t-H)},pe=()=>{y(),h.onFirstNonHeartbeatResponse?.(performance.now()-ue,v)},fe=h.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ie||void 0===ae||"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:ie,transportRunCalledAt:ue,firstRequestTakenAt:ae,firstMessageAt:de??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});h.onTtftBreakdown(void 0===r?e:{...e,transit:r},v)}:void 0,{interactionStream:me,execStream:ge,checkpointStream:we,kvStream:ye,done:ve}=function(e,t,r,n,o,s,i,a){const c=(0,Nn.Jt)(),l=(0,Nn.Jt)(),u=(0,Nn.Jt)(),d=(0,Nn.Jt)();let h=!1,p=!1;return{interactionStream:c,execStream:l,checkpointStream:u,kvStream:d,done:async function(){let f,m,g=!1,w=!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.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Os.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(h||(h=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{i?.()}catch(t){Os.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",js(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(g=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await c.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await l.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:o.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===o.message.case&&await d.write(o.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof Hn?e:co(e);return t instanceof qn&&function(e){return!0===e.isTransport||(e.cause instanceof Error?So(e.cause):ko(e.message))}(t)}(f)&&(Os.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)}),r.onStreamEnded(),m=void 0),g||o?.aborted||s?.aborted){if(!g&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${h}`;Os.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(Os.warn(e,t),m=new qn(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(Os.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new qn(t,{cause:f,isTransport:!0})):Os.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Ls(f)})}c.close(),l.close(),u.close(),d.close()}if(void 0!==m)throw m}()}}(e,le,B,he,$.signal,e.signal,pe,fe);let be;const Se={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};V[Symbol.dispose]();const ke=5e3;let _e;const Ce=()=>{_e=setTimeout((()=>{G.write(new Dn.KS({message:{case:"clientHeartbeat",value:new Dn.kA}})).then((()=>B.onClientSentHeartbeat()),(()=>{})),Ce()}),ke)},Ee=()=>{void 0!==_e&&(clearTimeout(_e),_e=void 0)};Ce();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new Ir.a({command:n.shellCommand?.command||"",parsingResult:new Ir.HO,skipApproval:!0}),a=s.get(Ar).execute(e,i,{execId:n.execId}),c=new Wo(me,o,new R.F8(G,(e=>new Dn.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async e=>{await Promise.all([j.track("handleShellStream",Us(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Wo(me,o,new R.F8(G,(e=>new Dn.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==K&&await Promise.race([K,ve.catch((()=>{}))]);const c=new R.F8(G,(e=>{if((0,ar.isMessage)(e,I.yT))return new Dn.KS({message:{case:"execClientMessage",value:e}});if((0,ar.isMessage)(e,I.$Y))return new Dn.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ar.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Mo(ge,c,O),v=new $n.hC(ye,new R.F8(G,(e=>new Dn.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),b=new u(we,Se,e);let S,k;const _={promise:new Promise(((e,t)=>{S=e,k=t})),resolve:S,reject:k};$.canceled?(_.resolve(),me.close()):$.signal.addEventListener("abort",(()=>{_.resolve(),me.close()}),{once:!0}),l.run($).then(_.resolve).catch(_.reject);const C=Promise.allSettled([j.track("streamSplitter",ve.finally((()=>{Ee(),a.close(),c.close()}))),j.track("execHandler",_.promise),t.run(e),j.track("checkpointController",b.run()),j.track("kvHandler",v.run(e)),j.track("conversationActionManager",a.run(e,{write:async t=>{await Ns({ctx:e,action:t,resources:s,blobStore:i,options:h,source:"queued_action"}),await G.write(new Dn.KS({message:{case:"conversationAction",value:t}}))}}))]);let x,P;const T={promise:new Promise(((e,t)=>{x=e,P=t})),resolve:x,reject:P};C.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Kn("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Kn("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?N():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:ve,lingerMs:h.softCancelLingerMs}).then((t=>{Os.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:p}),N()}))};$.canceled?(A(),T.reject(new Kn("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Kn("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],F=M[1],L=M[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new Gn("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===be;if(W){const t={..."rejected"===D.status?{streamSplitter:U(D)}:{},..."rejected"===F.status?{execHandler:U(F)}:{}};Object.keys(t).length>0&&Os.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!W)throw D.reason;if("rejected"===F.status&&!W)throw F.reason;$.canceled||await this.processUnprocessedMessages(E,a,Se,n,o,s,i,d,h,p,f,m,g,B,w,y)}finally{Ee(),W&&(W[Symbol.dispose](),W=void 0)}}catch(e){k.error=e,k.hasError=!0}finally{$s(k)}var _,C}async processUnprocessedMessages(e,t,r,n,o,s,i,a,c,l,u,d,h,p,f,m){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),w=r.getLatestCheckpoint();if(!w||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const v=r.getLatestCheckpoint();try{await this.runInternal(e,w,new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:y})}}),n,o,s,i,t,r,a,c,l,u,d,h,f,m,0,void 0,"agent.request.queuedMessage")}catch(e){throw v===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}new RegExp([String.raw`"type"\s*:\s*"response\.(?:output_text|reasoning_summary_text|reasoning_text|function_call_arguments|refusal)\.(?:delta|done)"`,String.raw`"(?:content|reasoning_content|reasoning|refusal)"\s*:\s*"(?!")`,String.raw`"tool_calls"\s*:\s*\[\s*\{`,String.raw`"type"\s*:\s*"content_block_delta"`].join("|"));var Hs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),qs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const zs=(0,Fn.createContextKey)(void 0,{description:"anysphere.callerContext"});function Gs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function Vs(e){return e instanceof Error?e:new Error(String(e))}function Ks(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(Vs(e)),t?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:Hs.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 Js(...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 Zs(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,l={})=>{const u=(0,c.fR)(i.withName(`rpc.${String(o)}`),{kind:qs.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),d=(0,c.fU)(u);let h;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,c.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}(u)),n){const e=n(u);e&&(o=Js(o,e))}const i=Js(l.headers,o),{signal:f,cleanup:m}=!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)}}}(u.signal,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,Fn.createContextValues)()).set(zs,u),w={...l,headers:i,signal:f,contextValues:g},y=s.call(e,a,w);return Gs(y)?Ks(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?Promise.resolve(y).then((e=>Gs(e)?Ks(e,d,h):(d?.setStatus({code:Hs.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(Vs(e)),d?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:Hs.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(Vs(e)),d?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Xs=r("node:crypto"),Qs=r("../utils/dist/workspace-paths.js");function Ys(){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 ei(e){return(0,s.join)(Ys(),(0,Qs.r_)(e))}var ti=r("node:fs/promises"),ri=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),ni=r("node:fs"),oi=r("../shell-exec/dist/api/index.js"),si=r("./src/agent/native/tree-sitter.webpack.cjs"),ii=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const ai=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(ii),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 si)),ci=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),li=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function ui(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=>li.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)ci.has(r.type)&&h(r,t)})(t),ci.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 di(e){return ui(ai(),e)}function hi(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function pi(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function fi(e,t){const r=pi(e,t);return hi(e,r)?r-1:r}function mi(e,t){const r=pi(e,t);return hi(e,r)?r+1:r}function gi(e,t){return t>0?e.length<=t?e:e.slice(0,fi(e,t)):""}function wi(e,t){return t>0?e.length<=t?e:e.slice(mi(e,e.length-Math.trunc(t))):""}let yi,vi;function bi(e,t){yi??=new TextEncoder,vi??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ki.o1)(e);try{return await(0,ti.realpath)(t)}catch{return t}},Ei=1048576,xi=52428800;var Pi=r("../utils/dist/test-resets.js");const Ii="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ri="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Ti=/\$\(|`|<\(|>\(/,Ai=/[;&|]/;let $i,Mi,Di,Oi;function Fi(){if(void 0===$i){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();$i=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return $i}function Ni(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 ji(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Li(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 Ui(){if(void 0===Oi){const e=(process.env[Ii]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Ii} (expected "allow" or "deny"); using "deny".`);const r=ji("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ri]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=ji(Ri)),Oi={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:ji("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Li("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Oi}function Bi(e,t,r={}){const n=[Ni(e),Ni(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 Wi(e,t){const r=function(){const e=Ui();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===Mi&&(Mi=Bi("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Mi);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Ti.test(e))return r;const s=(void 0===Di&&(Di=Bi("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Di);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ai.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ui();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,Pi.J)((function(){$i=void 0,Mi=void 0,Di=void 0,Oi=void 0}));var Hi=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function qi(e){if(!e)return;let t;return"allow"===e.default?t=Hi.h1.ALLOW:"deny"===e.default&&(t=Hi.h1.DENY),new Hi.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Hi.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function zi(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 Hi.h1.ALLOW:t.default="allow";break;case Hi.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,oi.T6)():(0,oi.Po)())}function Gi(e){switch(e){case"system":return Hi.Sz.SYSTEM;case"workspace":return Hi.Sz.WORKSPACE;default:return Hi.Sz.UNSPECIFIED}}function Vi(e){const t=function(e){switch(e){case Hi.Sz.SYSTEM:return"system";case Hi.Sz.WORKSPACE:return"workspace";case Hi.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Ki(e){if(!e)return{type:"insecure_none"};switch(e.type){case Hi.vc.INSECURE_NONE:case Hi.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Hi.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:zi(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,...Vi(e)};case Hi.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:zi(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Vi(e)};default:return{type:"insecure_none"}}}function Ji(e){if(e)return"insecure_none"===e.type?new Hi.Mw({type:Hi.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Hi.Mw({type:Hi.vc.WORKSPACE_READWRITE,networkAccess:(0,oi.$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:qi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Hi.Mw({type:Hi.vc.WORKSPACE_READONLY,networkAccess:(0,oi.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:qi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Hi.Mw({type:Hi.vc.INSECURE_NONE})}function Zi(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function Xi(e){let t="",r=!1;for(const n of e)Zi(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Qi(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const na={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function oa(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=na[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 Xi(t)}function sa({rule:e,command:t}){const r=Xi(e).trim();return 0!==r.length&&(null!==function(e){const t=Xi(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Qi(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=Yi(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Qi(e)&&(0===t.length||Qi(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Xi(t).trim(),oa(t).trim()].some((e=>function(e,t){const r=Yi(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(ta(e,s)&&ta(n,i))return!0}return e.includes("*")?ta(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ia({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=>sa({rule:e,command:t}))))return e}function aa(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 ca({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=ia({matchForms:ra({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:aa(n)}var la=r("../utils/dist/lru-cache.js");const ua=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],da="/Volumes";function ha(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function pa(e,t){if("darwin"!==t.platform)return[];const r=ha(e),n=r.toLowerCase(),o=ha(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...ua.map((e=>`${o}/${e}`)),da].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var fa=r("node:util"),ma=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),ga=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function wa(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const ya="utf8",va="utf8bom",ba="latin1",Sa={"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 ka(e){return Sa[e]||e}function _a(e){return e.startsWith("\ufeff")?e.slice(1):e}function Ca(e){const t=e.toLowerCase();return"latin-1"===t?ba:"utf-8"===t?ya:"utf-8-bom"===t||"utf-8 bom"===t?va:t}function Ea(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 xa=new fa.TextDecoder("utf-8",{fatal:!1}),Pa=new fa.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),Ia="�";function Ra(e){return xa.decode(e)}function Ta(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function Aa(e){let t=0,r=e.indexOf(Ia);for(;-1!==r;)t++,r=e.indexOf(Ia,r+1);return t}function $a(e,t){const r=e[t];let n,o=128,s=191;if(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 Ma(e){return e<128?1:e<2048?2:e<65536?3:4}var Da;!function(e){e.CRLF="CRLF",e.LF="LF"}(Da||(Da={}));const Oa=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Fa=new Set(Oa),Na=new fa.TextDecoder("utf-8",{fatal:!0}),ja=new fa.TextDecoder("latin1"),La=Buffer.from([239,187,191]),Ua={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Ba=8192,Wa="UTF-8",Ha="windows-1252",qa=/[^\u0000-\u007f\ufffd]/u,za=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ga=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Va=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ka=new Map([["windows-1251",za],["ISO-8859-5",za],["KOI8-R",za],["x-mac-cyrillic",za],["IBM866",za],["IBM855",za],["ISO-8859-7",Ga],["windows-1253",Ga],["windows-1255",Va],["ISO-8859-8",Va],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ja=/\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,Za=/[\p{L}\p{M}]+/gu,Xa=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Qa=new RegExp(`[A-Za-z]${Xa}{1,2}(?!${Xa})|^${Xa}{1,2}[A-Za-z]`,"u"),Ya=new Map,ec=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Oa]),tc=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i,rc=new Set([".ps1",".psm1",".psd1"]),nc=/[^\u0000-\u007f]/u;function oc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function sc(e){const t=oc(e);return Fa.has(t)}function ic(e){const t=oc(e);return{encoding:"binary",lineEnding:Da.LF,isBinaryFile:!0,isImageFile:tc.test(t),isVideoFile:Fa.has(t)}}async function ac(e,t){return(await cc(e,t)).text}async function cc(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,ti.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=hc(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=bc(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=_c(n,i),l=_a(a),u=c===ya&&(d=n).length>=La.length&&d[0]===La[0]&&d[1]===La[1]&&d[2]===La[2]?va:c;var d;return Sc(e,r,u),o.lineEnding===Da.CRLF?{text:l.replaceAll("\r\n","\n"),encoding:u}:{text:l,encoding:u}}async function lc(e,t){if("binary"===t.encoding)return void vc(e);let r;try{r=await(0,ti.stat)(e)}catch{return void vc(e)}r.size===t.buffer.byteLength?Sc(e,r,t.encoding):vc(e)}async function uc(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await dc(e)}catch{}const r=oc(e);if(ec.has(r))return ic(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of wc(e)){if(r>=100)break;try{const e=await dc(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:yc()}(t)}catch{return yc()}}(e,r):await dc(e)}catch{const t=oc(e);s=ec.has(t)?ic(e):yc()}const a=()=>i??=async function(e){try{const t=await(0,ti.stat)(e);if(!t.isFile()||t.size>tr)return;return await(0,ti.readFile)(e)}catch{return}}(e),c=bc(e,await async function(e){try{return await(0,ti.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Ca(o):c?r=Ca(c):(r=Ca(s.encoding),r!==ya&&r!==va||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:kc(r).encoding===ba?ba:e}(r,a))),r===ya&&!o&&function(e,t){return"win32"===process.platform&&rc.has(oc(e))&&nc.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,ti.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=va);const i=r===va||r===ya&&!o&&await Cc(e,La),u=Ua[ka(r)];i?l=La:u&&await Cc(e,u)&&(l=u),s={...s,encoding:i?va:r}}const u=wa(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=_a(_c(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=Ea(t),o=Ea(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?_a(t):t,p=s.encoding===va?ya:s.encoding,f=p===ya?await async function(e,t){if(!t.includes(Ia))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(Ia)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Pa.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=Ma(o);continue}const s=$a(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(Ia);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:fc(ma.decode(e.subarray(0,Ba),ka(Ca(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Ba,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:Wa,lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=Ra(e),s=e.length,Ta(o)||1024*Aa(o)<=s&&!qa.test(o)))return{encoding:Wa,lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=ga.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ka.get(a);return void 0!==c&&(a=function(e,t,r){const n=ka(Ca(t));if(!ma.encodingExists(n))return t;const o=ma.decode(e,n);return Ja.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of ma.decode(e,Ha).matchAll(Za))Qa.test(t)&&o++;return o>n}(e,o,r)?Ha:t}(e,a,c)),a!==Ha||function(e,t){const r=ka(Ca(t));return!ma.getDecoder(r).write(e).includes(Ia)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function pc(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return mc(t,r)}function fc(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return mc(r,t-r)}function mc(e,t){return 0===e&&0===t?Da.LF:e/(e+t)*100>=5?Da.CRLF:Da.LF}async function gc(e){const t=await(0,ti.open)(e,"r");try{const e=Buffer.allocUnsafe(Ba),{bytesRead:r}=await t.read(e,0,Ba,0);return e.subarray(0,r)}finally{await t.close()}}async function*wc(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,ti.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*wc(r)):n.isFile()&&(yield r)}}catch(e){return}}function yc(){return{encoding:ya,lineEnding:"win32"===process.platform?Da.CRLF:Da.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function vc(e){Ya.delete(e)}function bc(e,t){const r=Ya.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ya.delete(e)}function Sc(e,t,r){if(Ya.has(e)&&Ya.delete(e),Ya.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ya.size<=100)return;const n=Ya.keys().next().value;void 0!==n&&Ya.delete(n)}function kc(e){try{return{text:Na.decode(e),encoding:ya}}catch{const t=Ra(e);return Ta(t)?{text:t,encoding:ya}:{text:ja.decode(e),encoding:ba}}}function _c(e,t){const r=Ca(t);if(r===ya||r===va||"ascii"===r){const t=kc(e);return r===va&&t.encoding===ya?{text:t.text,encoding:va}:t}if(r===ba)return{text:ja.decode(e),encoding:ba};try{const t=ka(r);if(ma.encodingExists(t))return{text:ma.decode(e,t),encoding:r}}catch{}return kc(e)}async function Cc(e,t){try{return(await gc(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Ec=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),xc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class Pc{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Pc.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=hc(t);return r.isBinaryFile?Ra(t):_a(_c(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(Ac??=(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,ni.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),Ac),n=(0,s.join)(r,`cursorignore-${$c(e)}-${$c(t)}.txt`);if(await Mc(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,ti.writeFile)(i,t,"utf8"),await(0,ti.rename)(i,n),n}(e,r)}(e,await(0,ti.readFile)(e));return Rc.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function Oc(e){return Promise.all(e.map((e=>async function(e){const t=Tc.get(e);if(void 0!==t)return t;const r=Dc(e).catch((()=>e)).finally((()=>{Tc.delete(e)}));return Tc.set(e,r),r}(e))))}(0,Pi.J)((function(){Rc.clear(),Tc.clear()}));var Fc=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 Nc(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 jc(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 Oc(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,oi.spawnInSandbox)((0,oi.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=Nc(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 Ic.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{Fc(r)}}(),didTimeout:w}}var Lc=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 Uc;function Bc({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 Wc{constructor(e=()=>function(e=process.env){if(void 0!==Uc)return Uc;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}()){this.cache=new Pc({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(Bc(e))}walk(e,t){const r=Bc(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,Nc(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{Lc(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=jc(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 Hc=[{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 qc(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map(Hc.map((e=>[e.gitHost,e.apiHost]))),new Map(Hc.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Hc.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Hc.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Hc.map((e=>[e.apiHost,e.gitHost]))),new Map(Hc.map((e=>[e.apiHost,e.internalHost]))),new Map,function(e){const t=Hc.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t}("prod").gitHost;const zc=new Map;function Gc(e){if(void 0===e)return;if(zc.has(e))return zc.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||!qc(t.hostname))return;const r=function(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}`:""}(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 zc.size>=16384&&zc.clear(),zc.set(e,t),t}function Vc(e){return void 0!==function(e){const t=Gc(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 Kc=new WeakMap;function Jc(e,t,r){const n=performance.now();let o=Kc.get(t);void 0===o&&(o=new Map,Kc.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function Zc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Xc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Yc(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=Qc.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)??Yc(t)??t}}const Qc=new Set(["ftp","file","http","https","ws","wss"]);function Yc(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)}`))}function rl(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function nl(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""}const ol=[".gitignore",".cursorignore"],sl=new Map,il=new Map;function al(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 cl(e){const t=sl.get(e);return void 0!==t?t:al(sl,2048,e,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())}async function ll(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ki.DN)(e);return null===t?null:t}async function ul(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}(0,Pi.J)((function(){sl.clear(),il.clear()}));class dl{constructor(e,t,r){this.disposeRequested=!1,this.ignoreServicePromise=fl.init((0,be.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ignoreServicePromise.then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise.then((e=>{e.dispose()})).catch((()=>{})))}}const hl=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class pl{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=Ec().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class fl{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 la.q({max:2e3}),this.cursorIgnoreCache=new la.q({max:2e3}),this.gitRootCache=new la.q({max:1e4}),this.gitRemoteUrlCache=new la.q({max:200}),this.hasGitDirCache=new la.q({max:1e3}),this.gitParsedIgnoreCache=new pl(1e4),this.cursorParsedIgnoreCache=new pl(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new la.q({max:1e4}),this.unwalkedFolders=o.flatMap((e=>pa(e,s)))}static getRipwalkCache(){return fl.ripwalkCache??=new Wc,fl.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,ki.DN)(e)??(0,ki.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ki.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,ir.PH)(r,(async e=>{const t=await(0,ki.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=(await(0,ir.PH)(a,(async r=>{const n=await Jc(e,t,r);return null!==n&&pa(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([fl.initializeIgnoreMapping(u,".gitignore",c,i),fl.initializeIgnoreMapping(a,".cursorignore",l,i)]),new fl(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ki.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 fl.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,ti.access)(n,ti.constants.F_OK);const t=await ac(n),o=fl.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===rl(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=fl.deduplicateRootDirectories(e),i=await fl.promiseQueue.enqueueList(o,(e=>fl.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await ac(e),n=fl.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await fl.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,be.q6)(),o=[],i={root:e,includeGlobs:ol.map((e=>`**/${e}`)),excludeGlobs:[...el,...tl(e,r)],source:"ignore_scan"},a=fl.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}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=fl.parseIgnoreRules(await ac((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)=>Ec().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,ki.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,ki.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ki.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 fl.promiseQueue.enqueueList(o,(e=>fl.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,ki.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ki.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,ki.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,ti.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const n=e[t];e[t]=n?[...n,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ki.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()}dispose(){this.gitIgnoreCache=new la.q({max:1}),this.cursorIgnoreCache=new la.q({max:1}),this.gitRootCache=new la.q({max:1}),this.gitRemoteUrlCache=new la.q({max:1}),this.hasGitDirCache=new la.q({max:1}),this.directoryWalkPlacementCache=new la.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ac(e),n=fl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ac(e),n=fl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ki.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,ti.access)((0,s.join)(e,".git"),ti.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=await(this.teamSettingsService?.getTeamRepos());if(!t)return!1;const r=t.repos??[],n=t.disableLocalExecAllowlistEnforcement?[]:t.allowedRepos??[];if(0===r.length&&0===n.length)return!1;const o=await this.findGitRootsForFile(e);if(0===o.length)return this.checkNonRepoPathBlockedByAllowlist(e,n);let i=0===n.length,a=!1;for(const t of o){let o;if(this.gitRemoteUrlCache.has(t)?o=this.gitRemoteUrlCache.get(t):(o=await Zc((0,be.q6)(),this.gitExecutor,t),void 0!==o&&this.gitRemoteUrlCache.set(t,o)),void 0===o)continue;const c=o,l=(0,s.relative)(t,e)||".";for(const e of r)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;n.length>0&&!a&&(a=!0,i=n.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,ki.ZU)({basePath:r,targetPath:e}))return!1;const n=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,n))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,n))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ki.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ki.oL)((0,s.relative)(t,e)):(0,ki.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ki.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){return e.includes("*")?"*"===e.trim()||this.matchRepoUrlGlob(cl(e),cl(t)):cl(e)===cl(t)}matchGlob(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=il.get(e);if(void 0!==t)return t;let r;try{const t=xc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return al(il,2048,e,r)}(r)(t)}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();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=>this.doesRepoUrlMatch(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(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,be.q6)();for(const e of this.rootDirectories){const o=(0,ki.o1)(e);try{await(0,ti.access)((0,s.join)(o,".git"),ti.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,s.dirname)(o);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,ti.access)((0,s.join)(i,".git"),ti.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:[...r,...tl(o,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=fl.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,s.join)(o,e),n=(0,s.dirname)(r),i=(0,s.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Zc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}fl.promiseQueue=new ir.TJ({max:hl});const ml="agent-tools",gl=51380224;var wl=r("node:async_hooks");const yl=new wl.AsyncLocalStorage;function vl(e,t){return yl.run(e,t)}new wl.AsyncLocalStorage;var bl=r("../proto/dist/generated/agent/v1/utils_pb.js"),Sl=r("../utils/dist/safe-spawn-cwd.js"),kl=r("node:child_process"),_l=r("../utils/dist/workload-spawn.js");const Cl=(0,x.h)("local-exec:shell-output-encoding"),El=(0,fa.promisify)(kl.execFile),xl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,Pl=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function Il(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const Rl="㐀-䶿一-鿿豈-﫿",Tl=" -〿㈀-㏿︰-﹯＀-￯",Al="‐-※←-⇿─-◿★☆",$l="぀-ヿ",Ml=new Map([["cp932",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${Rl}${Tl}${Al}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const Dl=function(e){let t,r,n,o=!1,s=0;const i=()=>{s+=1;const e=s;n=async function(){const{stdout:e}=await(0,_l.D9)(El,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const s=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=Il(t,xl),o=Il(t,Pl);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 ma.encodingExists(t)?t:void 0}(t);return void 0!==n&&Ml.has(n)?n:void 0}(s),r=s,o=!0,n=void 0,Cl.info((0,be.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:s.oemcp??"none",acp:s.acp??"none"})}),(t=>{n=void 0,Cl.warn((0,be.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&&i(),{current:()=>("win32"===e&&!o&&void 0===n&&s<3&&i(),t),pages:()=>void 0!==r?r:"win32"!==e||s>=3&&void 0===n?"none":"pending",settled:()=>n??Promise.resolve()}}(process.platform),Ol=Buffer.alloc(0),Fl=/[\u0080-\uffff]/;function Nl(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 jl(){const e=new Ic.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Ll(e,t){return ma.decode(t,e,{stripBOM:!1})}const Ul=/[\xe0-\xef][\x80-\xbf]\?/;const Bl=10,Wl=Buffer.alloc(0),Hl=new Set([7,8,9,10,11,12,13,27]);function ql(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Vl={encoding:"utf8",skip:0};function Kl(e){const t=e();let r="utf8";const n={},o=()=>"utf8"===r?t:n[r]??=Gl(r);let s,i=!0,a=Wl,c=!1,l=0;const u=(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?Vl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Vl;const n=zl(e,r);if(-1!==n)return ql(e,r,n)?{encoding:r,skip:0}:Vl;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:ql(e,r,n)?o:Vl}if(-1===i)return t?Vl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Vl:void 0;if(0===e[i+1])return o}return Vl},d=e=>{if(e===r)return"";const t=o().end();return r=e,t},h=e=>"utf8"===r&&0!==e&&e<128,p=(e,n)=>{let p="",f=e;for(;;){if(i){const e=Math.min(f.length,512-a.length);let r;if(r=a.length>0?Buffer.concat([a,f.subarray(0,e)]):e===f.length?f:f.subarray(0,e),0===r.length)return p;const o=u(r,n||r.length>=512);if(void 0===o)return 1===r.length&&h(r[0])&&(p+=t.write(r),c=!0),a=Buffer.from(r),p;let m=o.skip,g=!1;if(c&&(m="utf8"===o.encoding?1:2,g=r[0]===Bl,c=!1),0===a.length)m>0&&(f=f.subarray(m));else{const t=r.subarray(m);f=f.subarray(e),f=0===f.length?t:0===t.length?f:Buffer.concat([t,f]),a=Wl}if(i=g,l=0,s=void 0,p+=d(o.encoding),g)continue}if(0===f.length)return p;if("utf8"===r&&!f.includes(0)&&!f.includes(254)&&!f.includes(255)){const e=f.lastIndexOf(Bl),r=-1===e?-1:f.length-e-1;if(-1===r||r>=2)return p+t.write(f);if(i=!0,0===r)return e>0&&f[e-1]===Bl&&(a=Buffer.of(Bl),c=!0),p+t.write(f);const n=f[f.length-1];return a=Buffer.of(n),c=h(n),p+t.write(c?f:f.subarray(0,e+1))}const e=zl(f,r,l,s);if(-1===e)return l+=f.length,s=f[f.length-1],p+o().write(f);p+=o().write(f.subarray(0,e)),f=f.subarray(e),i=!0}};return{write:e=>0===e.length?o().write(e):p(e,!1),peek(){if(!i||0===a.length)return"";const t=u(a,!0);if(void 0===t)return"";const r=c?"utf8"===t.encoding?1:2:t.skip,n=a.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Gl(t.encoding).write(n)},end(){const e=p(Wl,!0)+o().end();return i=!0,a=Wl,c=!1,l=0,s=void 0,e}}}var Jl=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},Zl=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 Xl=(0,x.h)("local-exec:shell-core"),Ql="win32"===process.platform,Yl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function eu(e){return`'${e.replace(/'/g,"'\\''")}'`}const tu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function ru(e){return tu.some((t=>e.includes(t)))?(0,Xs.createHash)("sha256").update(e).digest("hex"):e}function nu(e,t){return e[t]??process.env[t]}const ou=/^[A-Za-z_][A-Za-z0-9_]*$/,su=/CURSOR_SANDBOX/i;function iu(e){return ou.test(e)&&!su.test(e)}function au(e){return"function"==typeof e?e():e}function cu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function lu(e){let t=0,r=0;const n=e.length;for(;riu(e)&&!r.includes(e))),o=`builtin unset ${[...Yl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Yl){const r=nu(e,t);void 0!==r&&s.push(`builtin export ${t}=${eu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${eu(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("; ")}(y,b),void 0!==y.__CURSOR_SANDBOX_ENV_RESTORE&&(y.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=ru(e);t!==e&&(r=r.split(e).join(t))}return r}(y.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,S,b.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const k=function(e,t){const r=nu(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[]}}(nu(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=cu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=cu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=cu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=cu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,y),_=(0,oi.CG)(k??oi.BM);let C,E,x;k&&(yield{type:"start",sandboxed:"workspace_readonly"===_||"workspace_readwrite"===_}),t.askpassConfig&&!Ql&&(y.SUDO_ASKPASS=t.askpassConfig.helperPath,y.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,y.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=(this.options.outputFallbackEncoding??(()=>Dl.current()))(),I=()=>function(e){if(void 0===e)return jl();const t=Ml.get(e);return void 0!==t&&ma.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=Fl.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&&Ul.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Ol,i=0,a="utf8";const c=()=>{a="utf8",o.reset(),i=0},l=(t,n)=>{const s=n?Nl(t):0,c=t.subarray(0,t.length-s),l=c.toString("utf8");if("replacement"!==a){const t=c.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===l.length?"":l[l.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,u=function(e,t,r){let n=Ll(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s{const t=0===s.length?e:Buffer.concat([s,e]);if(s=Ol,"utf8"===a){const e=t.subarray(0,t.length-Nl(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(c(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(l.length))),-1===e?o.note(n):c(),i=u;continue}a="undecided"}const{text:h,keep:p}=l(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&c(),i=u}return r},end:()=>{const e=s;s=Ol;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):l(e,!1).text;return c(),t}}}(e,t):jl()}(P),R={stdout:Kl(I),stderr:Kl(I)},T=e=>{void 0!==u&&0!==e.length&&(u.file?u.file.write(e):u.buffer+=e)},A=function*(){const e={stdout:f,stderr:m};for(const t of["stdout","stderr"]){const r=R[t].end();0!==r.length&&(void 0!==u&&!0!==u.truncated&&T(r),e[t]||(yield{type:t,data:r}))}};for await(const r of i.execute(e,t.command,{signal:w,workingDirectory:l,env:y,sandboxPolicy:k,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:au(this.options.powershellUtf8Console),powershellUtf8ChildEnv:au(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:au(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:au(this.options.powershellWebRequestUtf8)})){C=0,E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=R[r.type],o="stdout"===r.type?f:m,i=void 0===u||!0===u.truncated;let a=!1;if(!o||!i){C=r.data.length;const c="stdout"===r.type?h:p,l=!o&&c+C<=Ei,f=void 0!==u&&!0!==u.truncated&&u.size+C<=gl;"stdout"===r.type?e=l:t=l;const m=!o&&!l,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&T(x),m||(x="")),(l||f)&&(E=n.write(r.data),a=!0),void 0!==u&&u.size+C>gl)u.truncated=!0;else if(f&&void 0!==u)if(u.size+=C,u.lineCount+=lu(r.data),u.file)u.file.write(E);else if(u.buffer+=E,u.size>u.threshold){const e=s.join(this.projectDir,ml);u.path=s.join(e,`${(0,Xs.randomUUID)()}.txt`);try{await(0,ti.mkdir)(e,{recursive:!0}),u.file=(0,ni.createWriteStream)(u.path),u.file.on("error",(e=>{d??=e})),u.file.write(u.buffer)}catch(e){d??=e instanceof Error?e:new Error(String(e)),u.truncated=!0}u.buffer=""}}a||n.end()}switch(r.type){case"stdout":e?(h+=C,E&&(yield{type:"stdout",data:E})):f||(x&&(yield{type:"stdout",data:x}),f=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:oi.Ls});break;case"stderr":t?(p+=C,E&&(yield{type:"stderr",data:E})):m||(x&&(yield{type:"stderr",data:x}),m=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*A();const e=Math.max(0,Math.round(performance.now()-o));let t;if(u?.file){if(u.truncated){const e=`\n... (output truncated at ${u.size} bytes) ...\n`;u.file.write(e),u.size+=e.length,u.lineCount+=wa(e)-1}const e=await new Promise((e=>u.file.end(e)));d??=e??void 0,d?await(0,ti.rm)(u.path,{force:!0}):t=new bl.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})}d&&void 0!==u?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${u.path}: ${d.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*A()}catch(e){r.error=e,r.hasError=!0}finally{Zl(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 hu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Jl(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Xl.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{Zl(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class pu{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 fu(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(aa(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function mu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return aa(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 gu(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new Ir.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new Ir.pZ({command:e,workingDirectory:t,reason:mu(r)})}}var wu=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 yu=(0,x.h)("local-exec:background-shell");function vu(e,t,r){return new xr.Lt({result:gu(e,t,r)})}class bu{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 Su(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 ku(e){e().catch((()=>{}))}class _u{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Si.L3.compile(e.config.pattern,Si.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=wi(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}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:Date.now()-this.startedAtMs}),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=me(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:`${gi(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=me(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&&yu.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 Cu{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 _u({shellId:t,outputPath:i,config:o,conversationId:r??fe,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&yu.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 Eu{async spawn(e,t){const r=new AbortController,n=new bu(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 oi.SandboxUnsupportedError||e instanceof uu)throw e}return ku((()=>Su(n,o))),n}async adopt(e){const t=new bu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,ku((()=>Su(t,e.eventIterator))),t}}function xu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Pu(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: ${xu(e.cwd)}\n`,n+=`command: ${xu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${xu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function Iu(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 Ru{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,ti.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();let g,w="running",y=!1,v=Promise.resolve();const b=async e=>{if(c)try{await c.write(e)}catch(e){}},S=t.shellId,k=s.join(r,`${S}.txt`),_=async()=>{if(!a)return;const e=Date.now()-f,r=Pu({pid:g,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},C=()=>(v=v.then(_).catch((()=>{})),v),E=()=>{void 0!==l&&(clearInterval(l),l=void 0)},x=async e=>{if(p)return;p=!0,g=e;const r=Date.now()-f,n=Pu({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:r});await(0,ti.writeFile)(k,n,"utf8"),l=setInterval((()=>{C()}),5e3)},P=async()=>{a||(a=await ni.promises.open(k,"r+")),c||(c=await ni.promises.open(k,"a"))},I=async(e,t)=>{if(!y){if(y=!0,E(),p||await x(),await P(),void 0!==t){const e=Date.now()-f,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(r)}w=e,await C()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await x(),await P()),await b(r.data);else if("stderr"===r.type)p||(await x(),await P()),await b(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 x(r.pid),await P());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`;b(`[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 x(),await P(),await b(Iu("stderr"));else d=!0,p||await x(),await P(),await b(Iu("stdout"));yield r}if(!y){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=xu(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await v,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,ti.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let i="running";const a=Date.now()-n,c=Pu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,ti.writeFile)(r,c,"utf8");const l=await ni.promises.open(r,"r+");let u;try{u=await ni.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=!1,f=!1,m=Promise.resolve();const g=async()=>{const t=Date.now()-n,r=Pu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},w=()=>(m=m.then(g).catch((()=>{})),m);let y=setInterval((()=>{w()}),5e3);const v=()=>{void 0!==y&&(clearInterval(y),y=void 0)},b=async()=>{if(!d){d=!0,v(),await m;try{await l.close()}catch{}try{await u.close()}catch{}}},S=async e=>{try{await u.write(e)}catch(e){}},k=async(t,r)=>{if(!h){if(h=!0,v(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(o)}i=t,await w()}},_={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await S(e.data):"stdout_trimmed"!==e.type||p?"stderr_trimmed"!==e.type||f?"exit"===e.type&&(await k(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await b()):(f=!0,await S(Iu("stderr"))):(p=!0,await S(Iu("stdout")))}return t.done&&await b(),t}catch(t){const r=e.abortController.signal.aborted;throw await k(r?"aborted":"failed"),await b(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}return await b(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:_})}}class Tu{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:pe(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??fe,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:Date.now()-o,...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.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},n,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.startTime,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 Au{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 $u{constructor(e,t,r,n,o,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new Au(s,i):s,c=o??function(e){const t=new Eu;return new Ru(t,e)}(n),l=new Cu(c,n,a);this.backgroundShellManager=new Tu(l,a)}getManager(){return this.backgroundShellManager}dispose(){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,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Ki(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ki.o1)(s),a=new Ir.HO(di(n).structured),l=ca({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new xr.Lt({result:{case:"rejected",value:new Ir.pZ({command:n,workingDirectory:i,reason:l})}});let u=o;if(yu.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}),zr(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId},o);if("block"===r.kind)return yu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),vu(n,i,r.reason);yu.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.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:Hr(t)},o);if("block"===r.kind)return yu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),vu(n,i,r.reason);u=r.policy,yu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Fi()&&(u=Wi(n,a)),u&&"insecure_none"!==u.type){const e=await ul(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}: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 xr.Lt({result:{case:"success",value:new xr.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof oi.SandboxUnsupportedError){const o=u?.type??"unknown";return yu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new xr.Lt({result:{case:"sandboxUnsupported",value:new Ir.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new xr.Lt({result:{case:"error",value:new xr.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const Mu={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Du=Ln.object({command:Ln.string().optional(),args:Ln.array(Ln.string()).optional(),env:Ln.record(Ln.string(),Ln.string()).optional(),url:Ln.string().optional(),headers:Ln.record(Ln.string(),Ln.string()).optional(),cwd:Ln.string().optional(),envFile:Ln.string().optional(),auth:Ln.object({CLIENT_ID:Ln.string(),CLIENT_SECRET:Ln.string().optional(),scopes:Ln.array(Ln.string()).optional()}).optional(),enabledTools:Ln.array(Ln.string()).optional(),placement:Ln.enum(["server","client"]).optional(),tls:Ln.object({caBundle:Ln.string().trim().min(1).max(131072)}).optional()}),Ou=Ln.object({mcpServers:Ln.record(Ln.string(),Du).optional()}),Fu=Ln.enum(["canvas"]),Nu=Ln.array(Fu).transform((e=>[...new Set(e)].sort()));class ju extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Lu(e){const t=e.trim();if(!t)throw new ju("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new ju("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new ju("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new ju("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 ju("Missing plugin name before @",e);if(!s)throw new ju("Missing source after @",e);if(!r.test(o))throw new ju("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new ju("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 ju("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 ju("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 ju("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new ju("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 ju("Missing marketplace name",e);if(!r.test(a))throw new ju("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function Uu(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 Bu(e){return e.sourceInfo.name}function Wu(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Hu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function qu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const zu=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Gu(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=>zu.has(e)))}const Vu=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Ku=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Ju=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Zu(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Ju.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Xu(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Xu(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Xu(r,t)}else for(const[,r,n,o]of e.matchAll(Vu)){const e=r??n;if(void 0===e||Ku.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Qu(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Xu(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:Zu(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.`,...Gu(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var Yu=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const ed=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),td=/^v?(\d+\.\d+(?:\.\d+)?)$/;function rd(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 nd(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=td.exec(e);if(null!==t)return t[1]}}function od(e){return void 0===e?{kind:"absent"}:ed.has(e)?{kind:"supported",id:e,version:nd(e)??e}:{kind:"unsupported",id:e}}const sd=10485760,id=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,ad=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],cd=[".cursor-plugin",".claude-plugin"],ld=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ud=Ln.object({source:Ln.literal("github"),repo:Ln.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),dd=Ln.object({source:Ln.literal("url"),url:Ln.string().url().endsWith(".git","URL must end with .git"),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),hd=Ln.object({source:Ln.literal("git-subdir"),url:Ln.string().url().endsWith(".git","URL must end with .git"),path:Ln.string().min(1),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),pd=Ln.union([Ln.string(),ud,dd,hd]),fd=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,md='Must be a semver version (X.Y.Z) or "never"',gd=Ln.object({cursor:Ln.string().regex(fd,md).optional(),sand:Ln.string().regex(fd,md).optional(),sandMobile:Ln.string().regex(fd,md).optional()}),wd=Ln.object({name:Ln.string().min(1,"Author name is required"),email:Ln.string().email().optional()}),yd=Ln.enum(["string","number","integer","boolean","object","array","null"]),vd=Ln.union([yd,Ln.array(yd).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Ln.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function bd(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Ln.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:Ln.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:Ln.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:Ln.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:Ln.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:Ln.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:Ln.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const Sd=Ln.lazy((()=>Ln.object({type:vd.optional(),title:Ln.string().optional(),description:Ln.string().optional(),format:Ln.string().optional(),writeOnly:Ln.boolean().optional(),placeholder:Ln.string().optional(),default:Ln.unknown().optional(),enum:Ln.array(Ln.any()).nonempty().optional(),const:Ln.unknown().optional(),properties:Ln.record(Ln.string(),Sd).optional(),required:Ln.array(Ln.string()).optional(),additionalProperties:Ln.union([Ln.boolean(),Sd]).optional(),items:Ln.union([Sd,Ln.array(Sd)]).optional(),minLength:Ln.number().int().nonnegative().optional(),maxLength:Ln.number().int().nonnegative().optional(),minimum:Ln.number().optional(),maximum:Ln.number().optional(),exclusiveMinimum:Ln.number().optional(),exclusiveMaximum:Ln.number().optional(),multipleOf:Ln.number().positive().optional(),minItems:Ln.number().int().nonnegative().optional(),maxItems:Ln.number().int().nonnegative().optional(),uniqueItems:Ln.boolean().optional(),minProperties:Ln.number().int().nonnegative().optional(),maxProperties:Ln.number().int().nonnegative().optional()}).strict().superRefine(bd)));function kd(e){const t=Sd.superRefine(((e,t)=>{Ed(e)&&"object"===e.type||t.addIssue({code:Ln.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?xd(t.data)?{success:!0,data:t.data}:{success:!1,error:new Ln.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const _d=Ln.unknown().superRefine(((e,t)=>{const r=kd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!xd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),Cd=(Ln.object({name:Ln.string().min(1).transform((e=>e.toLowerCase())).refine((e=>id.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ln.string().optional(),source:pd,description:Ln.string().optional(),version:Ln.string().optional(),author:wd.optional(),publisher:Ln.string().min(1).optional(),homepage:Ln.string().url().optional(),repository:Ln.string().url().optional(),license:Ln.string().optional(),keywords:Ln.array(Ln.string()).optional(),capabilities:Nu.optional(),logo:Ln.string().optional(),category:Ln.string().optional(),tags:Ln.array(Ln.string()).optional(),minClientVersions:gd.optional(),strict:Ln.boolean().default(!0),commands:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),agents:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),skills:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),rules:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),hooks:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]).optional(),variables:_d.optional(),mcpServers:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown()),Ln.array(Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]))]).optional()}),Ln.object({description:Ln.string().optional(),version:Ln.string().optional(),pluginRoot:Ln.string().optional()}),Ln.object({name:Ln.string().min(1).regex(id,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ln.string().optional(),description:Ln.string().optional(),version:Ln.string().optional(),author:wd.optional(),publisher:Ln.string().min(1).optional(),homepage:Ln.string().url().optional(),repository:Ln.string().url().optional(),license:Ln.string().optional(),logo:Ln.string().optional(),keywords:Ln.array(Ln.string()).optional(),capabilities:Nu.optional(),minClientVersions:gd.optional(),commands:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),agents:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),skills:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),rules:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),hooks:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]).optional(),variables:_d.optional(),mcpServers:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown()),Ln.array(Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]))]).optional()}));function Ed(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xd(e){return Ed(e)&&"object"===e.type}function Pd(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Id(e,t){if(Ed(e)&&"string"==typeof e.name){const t=Pd(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Pd(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,Xs.randomUUID)()}`}(t)}function Rd(e){if(Ed(e)&&Ed(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 Td(e){return"string"==typeof e?e:void 0}function Ad(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function $d(e){return"string"==typeof e?e:Ad(e)}function Md(e){if(!Ed(e)||!Ed(e.metadata))return;const t={description:Td(e.metadata.description),version:Td(e.metadata.version),pluginRoot:Td(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Dd(e){if(!Ed(e))return;const t=Td(e.name);if(void 0===t||0===t.length)return;const r=Td(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Od(e){if("string"==typeof e||Ed(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Ed(e)));return t.length>0?t:void 0}}function Fd(e){if("string"==typeof e||Ed(e))return e}function Nd(e){if(void 0===e)return;const t=kd(e);return t.success?t.data:void 0}function jd(e,t={}){if(e.length>sd)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(!Ed(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(!Ed(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:Ed(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Td(n.ref),sha:Td(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Td(n.ref),sha:Td(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:Td(n.ref),sha:Td(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Td(n.ref),sha:Td(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Td(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?Pd(e.name):"")||function(e){if("string"==typeof e){const t=Pd((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Pd(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Pd((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=Pd((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=Nu.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=gd.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:Td(e.displayName),source:r,description:Td(e.description),version:Td(e.version),author:Dd(e.author),publisher:Td(e.publisher),homepage:Td(e.homepage),repository:Td(e.repository),license:Td(e.license),keywords:Ad(e.keywords),logo:Td(e.logo),category:Td(e.category),tags:Ad(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:$d(e.commands),agents:$d(e.agents),skills:$d(e.skills),rules:$d(e.rules),hooks:Fd(e.hooks),variables:Nd(e.variables),mcpServers:Od(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:Id(r,t),owner:Rd(r),description:Td(r.description),plugins:n,metadata:Md(r),skippedPluginEntries:o}}}function Ld(e){if(e.length>sd)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=od(rd(t)),n=Cd.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 Ud(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 Bd(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Wd(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new Yu.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Hd=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const qd=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,zd=/\$%7B([^%/?#]+?)%7D/gi;function Gd(e,t){return Vd(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 Vd(e,t){if("string"==typeof e)return function(e,t){return e.replace(zd,"${$1}").replace(qd,((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=>Vd(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]=Vd(o,t);return r}return e}function Kd(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Jd=[".mcp.json","mcp.json"],Zd=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Xd(e,t){if(!function(e){return Zd.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 Qd(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Yd(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Jd.map((e=>void 0!==t?`${t}/${e}`:e))}function eh(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=Kd(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Kd(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?Kd(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Kd(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Gd(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Gd(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 th(e,t,r){try{const n=(0,Hd.qg)(e),o=rd(n);if(void 0!==o){const e=r?.log??Mu;"unsupported"===od(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=nd(e),n=nd(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=Ou.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:eh(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Xd(e,t)&&Qd(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Ou.safeParse({mcpServers:a});if(e.success)return i?e.data:eh(e.data,t,r)}return null}catch{return null}}function rh(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function nh(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Jd,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=th(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(!Bd(i))return;const a=await t(i);if(null===a)return;const c=th(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&rh(s,c.mcpServers,n(i))},a=e=>{const t=th(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&rh(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}}}function oh(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}var sh=r("node:stream"),ih=r("node:stream/promises"),ah=r("node:zlib"),ch=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const lh=".cache-complete";function uh(e){return sr(e)}function dh(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function hh(e,t){return function(e,t,r,n){const o=[t,r];return void 0!==n&&o.push(n),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...o):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...o].join("/"):(0,s.join)(e,...o)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?uh(t.version):void 0)}class ph{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return hh(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=dh({parent:t,name:lh});return(await(0,ti.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,ti.mkdir)(t,{recursive:!0});const r=sh.Readable.from(e.tarball);return await(0,ih.pipeline)(r,(0,ah.createGunzip)(),(0,ch.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=hh(this.cacheRoot,e);try{return(await(0,ti.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,ti.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=hh(this.cacheRoot,e);await(0,ti.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=>uh(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,ti.writeFile)(dh({parent:t,name:lh}),"")}}function fh(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 mh=[["safe.bareRepository","explicit"]],gh=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],wh=[["core.quotePath","false"]];function yh(e){const t="allow-hooks"===e?gh.filter((([e])=>"core.hooksPath"!==e)):gh;return[...mh,...t]}const vh=(0,fa.promisify)(kl.execFile),bh=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),Sh=new Set(["diff","show","blame","log","whatchanged"]);function kh(e){for(let t=0;tArray.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});return xh("git",[...Ph(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const Th=/^[0-9a-f]{7,40}$/i,Ah=/^[0-9a-f]{40}$/i;function $h(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 Mh(e,t,r){const n=t.trim();if(Ah.test(n))return{fullSha:n.toLowerCase()};if(Th.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Rh(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return $h(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 Rh(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=$h(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 Rh(["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=$h(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Dh=ld.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 Oh;function Fh(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 Nh(e){const t=[];for(const r of e){const e=Fh(r);if(null===e)return"all";t.push(e)}return t}async function jh(e,t){const r="all"===e?"all":Nh(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Oh??=(async()=>{try{const{stdout:e}=await Rh(["--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}})(),Oh));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Dh,...o])]):[]};var o}function Lh(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Uh(e,t,r){await Rh(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Bh(e){try{await(0,ti.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Rh(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Wh(e,t,r){if("all"!==t&&0===t.length)return;if(!await Bh(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Rh(["sparse-checkout","disable"],n);const o=Nh(t);"all"!==o?await Rh(["sparse-checkout","add","--",...o],n):await Rh(["sparse-checkout","disable"],n)}(0,Pi.J)((function(){Oh=void 0}));const Hh=/\.git$/i,qh=new Set(["account","dashboard"]);function zh(e){return e.replace(Hh,"")}function Gh(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Vh(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Kh(e){return e.toLowerCase().split(".").includes("gitlab")}function Jh(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function Zh(e){const t=e.toLowerCase();return Kh(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Xh(e){return Vh(e)?"github":Kh(e)?"gitlab":Jh(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Qh(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);qc(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=zh(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:Xh(r),owner:s.owner,repo:s.repo,host:r}}function Yh(e){const t=ep(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 ep(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function tp(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Qh(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Kh(r.host)){const e=ep(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=zh(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=ep(e.trim());if(null!==t&&Jh(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Gh(t),o=Gh(r);if(void 0===n||void 0===o||qh.has(n.toLowerCase()))return;const s=zh(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=ep(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=zh(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!qc(e.host)&&null===Zh(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=np(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Yh(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Zh(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function rp(e){const t=tp(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 np(e){return Vh(e)?"github.com":e}function op(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 sp(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function ip(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}const ap=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 cp(e){const t=sr(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":ap.has(t.toLowerCase())?`_${t}`:t}const lp=18e5,up=6e5,dp={recursive:!0,force:!0,maxRetries:3},hp=["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"],pp=["enotempty: directory not empty, rename","/_staging/"],fp=["upload-pack: not our ref","server does not allow request for unadvertised object"];function mp(e){const t=String(e).toLowerCase().replaceAll("\\","/");return hp.some((e=>t.includes(e)))?"user_git_access":pp.every((e=>t.includes(e)))?"local_cache_race":fp.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function gp(e){return"object"==typeof e&&null!==e&&(!0===e.killed||gp(e.cause))}function wp(e){return gp(e)?"killed_by_budget":mp(e)}function yp(e){const t=tp(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=Qh(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:np(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const vp=new Map;class bp{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?lp:void 0}localTimeoutMs(){return this.sparsePluginClones?up:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Ih(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await jh(n?.materialize??"all",this.sparsePluginClones);await Rh(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Uh(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Rh(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Rh(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Lh(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,Xs.randomUUID)());return await(0,ti.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,ti.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,ti.rm)(t,dp),await(0,ti.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,ti.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,ti.stat)(n);r-o.mtimeMs>bp.STALE_STAGING_THRESHOLD_MS&&await(0,ti.rm)(n,dp)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,cp(e),cp(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=yp(e);return(0,s.join)(this.cacheRoot,cp(r),...n.map(cp),cp(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=yp(e);return(0,s.join)(this.cacheRoot,cp(t),...r.map(cp))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=cp(t);try{const e=await(0,ti.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,ti.rm)((0,s.join)(n,e.name),dp))))}catch{}if(void 0!==r)try{await(0,ti.rm)(r,dp)}catch{}}async ensureCloned(e,t,r,n=Mu,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,ir.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Mu){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Wh(e,t,{extraGitConfig:Ih(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:wp(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:wp(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,ir.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(vp.get(r)??Promise.resolve()).catch((()=>{})).then(t);vp.set(r,n);try{return await n}finally{vp.get(r)===n&&vp.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:rp(t);if(null!==a)try{i=(await Mh(a,s,{sshBatchMode:!0,extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&gp(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:mp(e)}),a=null,i=(await Mh(t,s,{extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Mh(t,s,{extraGitConfig:Ih(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 Bh(c);return e&&await Wh(c,o,{extraGitConfig:Ih(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,ti.utimes)(l,e,e).catch((()=>{}))}),bp.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&&gp(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:wp(e)}),await(0,ti.rm)(l,dp),await(0,ti.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=wp(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,ti.rm)(l,dp)}catch{}}}async isCloneComplete(e){try{if(!(await(0,ti.stat)(e)).isDirectory())return!1;const t=await(0,ti.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,ti.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return ip(e,t)}async copyPluginToDir(e,t){await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.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 ld){const n=(0,s.join)(e,r);let o;try{o=await(0,ti.readFile)(n,"utf-8")}catch{continue}const i=jd(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=Ud(n.source,r.metadata?.pluginRoot);return o&&Bd(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=Ud(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":Bd(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):[]}}bp.STALE_STAGING_THRESHOLD_MS=3e5,bp.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const Sp=(0,fa.debuglog)("cursor-plugins");function kp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _p(e){return kp(e)?e:void 0}function Cp(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function Ep(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 xp(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Np(e,t.gitUrl)?e:r:e}function Pp(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function Ip(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=Ep(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Rp="backend-git://";function Tp(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Rp}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Ap(e){if(!e.startsWith(Rp))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 $p="backend-release://";function Mp(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${$p}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Dp(e){if(!e.startsWith($p))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 Op=/^[0-9a-f]{7,40}$/i;function Fp(e){let t;try{t=yp(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Np(e,t){if(e.trim()===t.trim())return!0;const r=Fp(e),n=Fp(t);return null!==r&&r===n}const jp=104857600;async function Lp(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(!(kp(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>kp(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>jp)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||!Up(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||!Up(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>jp)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,Xs.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,ti.mkdir)(n,{recursive:!0});const u=await(0,ti.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,ti.writeFile)(d,c),await(0,ti.mkdir)(h,{recursive:!0});let e=0,t=0;await ch.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,ti.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,ti.readdir)(e)).some((e=>cd.includes(e)))&&(a=e)}const p=await(0,ti.readdir)(a);await Promise.all(p.map((e=>(0,ti.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,ti.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function Up(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Bp{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??Mu,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new bp(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=Ih(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:rp(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 Mh(e,t,n):await Mh(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&gp(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}};for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=Ep(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=Cp({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;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,Xs.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:_p(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=xp(c,r),d=Ip(e,o),h=fh(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?Mp({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Tp(g,d,t.gitPath??void 0);const w=Pp(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Np(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:Tp(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:_p(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}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=Ap(e.downloadUrl);return!(!r||!Np(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,ti.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,ti.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${sr(t.name)}.md`,o=[];o.push(`description: ${sp(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${sp(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,ti.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,ti.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${sr(t.name)}.md`,o=t.description?`---\ndescription: ${sp(t.description)}\n---\n\n`:"";await(0,ti.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,ti.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&op(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,ti.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,ti.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,ti.mkdir)(c,{recursive:!0}),await(0,ti.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,ti.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===Dp(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)&&gp(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=Mu,n,i){const a=i?.sparsePluginClones??!1,c=a?lp:void 0,l=Dp(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Lp(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=ip(r,e.gitPath);await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,ti.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Lp(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Ap(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Mu,o,s="all",i=!1){const a=performance.now(),c=Op.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?lp:void 0,h=i?up:void 0,{sparse:p,sparseDirs:f}=await jh(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Uh(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Rh(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Rh(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Rh(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Rh(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Rh(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Rh(["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:rp(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&gp(t))throw t;await(0,ti.rm)(r,{recursive:!0,force:!0}),await(0,ti.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Lh(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);Sp("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?Nh([u.gitPath]):[],a),u.gitPath)o=ip(d,u.gitPath);else{const t=await async function(e,t){for(const r of ld){const n=(0,s.join)(e,r);let o;try{o=await(0,ti.readFile)(n,"utf-8")}catch{continue}const i=jd(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=Ud(c.source,a.metadata?.pluginRoot);return l&&Bd(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 Wh(d,Nh([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=ip(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 Wh(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,ti.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Ih(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=Nh(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?Nh([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,Nh([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 Wp(e,t,r,n,o){return new Bp(e,t,r,n,o)}var Hp=r("node:url"),qp=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const zp=()=>({});function Gp(e,t){return qp(e,{...t,engines:{...t?.engines,js:zp,javascript:zp}})}function Vp(e,t,r){return qp.stringify({content:e,data:{}},t,r)}function Kp(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Jp(e,t){if(Object.hasOwn(e,t))return e[t]}function Zp(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?Kp(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===Jp(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Kp(t.projectPath)===a&&!0===Jp(i,e))))),r||!0!==Jp(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 Xp=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");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=Xp.Ay.load(t[1],{schema:Xp.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=Jd.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(!Bd(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(!Bd(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(!Bd(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=>nh(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:Qu(a??i),configs:l}}}function lf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uf(e){return!!lf(e)&&(void 0===e.enabledPlugins||lf(e.enabledPlugins))}function df(e){return JSON.parse(e)}function hf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function pf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=df(await(0,ti.readFile)(n,"utf-8"));uf(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=df(await(0,ti.readFile)(o,"utf-8"));uf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}async function ff(e){try{return(await(0,ti.lstat)(e)).isSymbolicLink()}catch{return!1}}async function mf(e){if(await ff(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,ti.readFile)(e,"utf-8")}async function gf(e){if((await(0,ti.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function wf(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 yf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,ti.realpath)(e),n=ip(t,r),o=await(0,ti.realpath)(n);if(ip(t,o),!(await(0,ti.stat)(o)).isFile())return;return await gf(o),(0,Hp.pathToFileURL)(o).href}catch{return}}function vf(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 bf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Sf(e,t){return vf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function kf(e,t,r){let n;for(const o of ad){const i=(0,s.join)(e,o);let a;try{if(await ff(i))continue;if(!(await(0,ti.stat)(i)).isFile())continue;await gf(i),a=await mf(i)}catch{continue}const c=Ld(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 yf({installPath:e,logo:l.logo}),S=vf(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&&!bf(S))continue;if(!g&&!C){n=n?{...n,fields:Sf(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=Sf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||bf(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 _f(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,ti.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return ip(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,ti.realpath)(t);try{return ip(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,ti.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,ti.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 gf(i);const l=await(0,ti.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,ti.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Cf(r,o.skills,e),xf(r,o.agents,e),Pf(r,o.commands,e),Ef(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Cf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Ef(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Kd(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function xf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Tf({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Pf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Af({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function If(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 Rf({content:e,relativePath:t}){try{const r=Gp(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:If(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Tf({content:e,relativePath:t}){try{const n=Gp(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 Af({content:e,relativePath:t}){try{const r=Gp(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 $f(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Mf(e,t,r){const n=r??$f(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of ad){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=rd(a);const c=Ld(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return nh(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Bd(t))return null;const r=(0,s.join)(e,t);try{return await ff(r)?null:(await(0,ti.stat)(r)).isFile()?(await gf(r),await mf(r)):null}catch{return null}}}(e),{fallbackFileNames:Yd(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Df(e,t,r){const n=await Mf(e,void 0,{log:r});if(n)return n;for(const n of ld){const o=(0,s.join)(e,n);try{if(!(await(0,ti.stat)(o)).isFile())continue;const n=await(0,ti.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Nf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(jf),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(!Bd(n))continue;const o=(0,s.join)(e,n);try{await gf(o);const t=th(await mf(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 Of=new Set(Object.values(Ce));function Ff(e){return Of.has(e)}function Nf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jf(e){return!(!Nf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Lf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Ff(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Kd(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Kd(e.prompt,t)}:e)));return{...e,hooks:r}}async function Uf(e,t,r,n){if("object"==typeof r){const o=Bf(r,t);return o&&"config"in o?{config:Lf(o.config,e),...void 0!==n&&{sourcePath:n}}:o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Bd(t))return;o=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else o=(0,s.join)(e,"hooks","hooks.json");try{if(await ff(o))return;if(!(await(0,ti.stat)(o)).isFile())return}catch{return}try{await gf(o),i=await(0,ti.readFile)(o,"utf-8")}catch{return}try{a=JSON.parse(i)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const c=Bf(a,t);return c&&"config"in c?{config:Lf(c.config,e),sourcePath:o}:c}function Bf(e,t){const r=function(e){if(!Me(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(Me(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"===r){const r=_t(e);return r.isValid&&_t(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===r){if(!(Nf(n=e)&&Nf(n.hooks)&&Object.keys(n.hooks).length>0))return;const r=Le(e.hooks),o=_t(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}var n}async function Wf(e,t,r,n){const o=n?.log??Mu,s=await kf(e,t,o),i={...$f(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([_f(e,s?.manifestOptions),Mf(e,r,i),Uf(e,t,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 Hf(e,t,r){const n=r?.log??Mu,o=await kf(e,t.raw,n),[s,i,a]=await Promise.all([_f(e,o?.manifestOptions),Df(e,t,n),Uf(e,t.raw,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 Wf(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 zf(e,t,r={}){const n=r.log??Mu,o=performance.now(),i=await async function(e){const t=hf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=df(await(0,ti.readFile)(r,"utf-8"));return lf(n=e)&&lf(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=hf(e),r=(0,s.join)(t,"settings.json");try{const e=df(await(0,ti.readFile)(r,"utf-8"));return uf(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 Zp(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=Zp(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,ir.PH)(c,(async e=>({workspacePath:e,settings:await pf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=Lu(e),s=await Hf(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(Lu(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}async function Gf(e){const t=e.log??Mu,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new ph(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))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,ti.mkdir)(o,{recursive:!0});try{await n.installPlugin(e,o),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,ti.rm)(o,{recursive:!0,force:!0})}catch{}throw e}s=o}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const n=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:n.message,errorType:wf(n)});const o=e.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:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:o,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,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 Vf(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 Kf(e){return Vf(e)??`path:${e.installPath}`}function Jf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Zf(e,t){const r=[];for(const o of e){const e=Uu(o.identifier),i=`plugin:${e}`,a=Bu(o.identifier),c=Wu(o.identifier),l=Hu(o.identifier),u=qu(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}(0,s.join)((0,o.homedir)(),".claude","plugins","marketplaces");const Xf=Ln.object({path:Ln.string(),name:Ln.string().optional(),description:Ln.string().optional(),globs:Ln.array(Ln.string()).optional(),alwaysApply:Ln.boolean().optional(),content:Ln.string(),environments:Ln.array(Ln.string()).optional(),disabledEnvironments:Ln.array(Ln.string()).optional()}),Qf=Xf.extend({name:Ln.string()}),Yf=Ln.object({path:Ln.string(),name:Ln.string(),description:Ln.string().optional(),tools:Ln.array(Ln.string()).optional(),model:Ln.string().optional(),prompt:Ln.string(),permissionMode:Ln.enum(["default","readonly"]).optional()}),em=Ln.object({path:Ln.string(),name:Ln.string(),description:Ln.string().optional(),argumentHint:Ln.string().optional(),content:Ln.string()}),tm=Ln.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),rm=Ln.object({config:tm,sourcePath:Ln.string().optional()}),nm=Ln.custom((e=>"object"==typeof e&&null!==e));function om(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}}Ln.object({schemaVersion:Ln.number().int(),displayName:Ln.string().optional(),description:Ln.string().optional(),authorName:Ln.string().optional(),skills:Ln.array(Xf),rules:Ln.array(Qf),agents:Ln.array(Yf),commands:Ln.array(em),mcpConfig:Ou.extend({mcpServerSourcePaths:Ln.record(Ln.string(),Ln.string()).optional()}).optional(),hooks:rm.optional(),hooksError:Ln.string().optional(),capabilities:Ln.array(Ln.string()),variablesSchema:nm.optional()}),Error;class sm extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function im(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function am(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function cm(e){try{return am(await(0,ti.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 lm(e){const t=await cm(e);return void 0===t?[]:function(e){const t=function(e){const t=am(e);if(0===t.trim().length)return{};const r=[],n=(0,Hd.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Hd._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new sm(`.cursor/settings.json contains syntax errors: ${e}`)}if(!im(n))return{};const o=n.plugins;if(void 0===o)return{};if(!im(o))return{};const s={};for(const[e,t]of Object.entries(o))im(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||om(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function um(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var dm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const hm=(0,fa.debuglog)("agent-skills-catalog-cache");function pm(e){return(0,Xs.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function fm(e){try{return(await(0,ti.stat)(e)).mtimeMs}catch{return}}function mm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const gm=[".kits","cursor-pages"],wm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},ym=[{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},wm],vm=(new Set(ym.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function bm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function Sm(e){const t=bm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return ym.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&&vm.has(o)}function km(e){return{dirPath:(0,s.join)(e,wm.configDir,wm.subdir),scope:"builtin",source:"builtin"}}const _m="canvas";function Cm(e,t){return{dirPath:(0,s.join)(km(e).dirPath,...gm),scope:"builtin",source:"builtin"}}function Em(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return bm(r.slice(n.length+1))}function xm(e,t){const r=Em(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Pm(e){return ym.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Im(e,t){return Pm(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Rm(e,t){return Pm(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Tm=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 Am(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const $m=ym.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Am(e)}[/\\\\]${Am(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Mm=/[/\\]\.cursor[/\\]rules[/\\]/i,Dm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Om=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Fm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Om.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Mm.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Dm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Nm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Nm.ripwalkCache??=new Wc,Nm.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,c.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||pa(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 Jc(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(),l=this.buildIncludeGlobs(a),u={root:this.root,includeGlobs:l,excludeGlobs:el,followSymlinks:!0,source:"nested_extensibility"},d={rules:[],skills:[],markdown:[],agents:[]},h=Nm.getRipwalkCache();try{const e=h.walk(r.ctx,u);try{for await(const t of e.lines){const e=Fm(t,a);e&&d[e].push((0,s.resolve)(this.root,t))}}finally{h.delete(u)}}catch{}return r.span.setAttribute("nested_extensibility.rules",d.rules.length),r.span.setAttribute("nested_extensibility.skills",d.skills.length),r.span.setAttribute("nested_extensibility.markdown",d.markdown.length),r.span.setAttribute("nested_extensibility.agents",d.agents.length),d}catch(e){t.error=e,t.hasError=!0}finally{Tm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const jm=new Set(["node_modules","__pycache__","dist","build"]);async function Lm({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,ti.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,ti.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,ti.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,ti.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||jm.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 Um={agentStoreSkillsDirs:[],userHomeDirectory:""};function Bm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Wm(e,t){const r=Bm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Bm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Hm(e),inAgentStore:!1}}function Hm(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 qm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Wm(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 zm=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},Gm=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 Vm=(0,x.h)("local-exec:cursor-rules");function Km(e){return"/"===e||"\\"===e}function Jm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Zm(e){return await Lm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Xm(e){let t;try{t=await ac(e)}catch(t){return{skillFilePath:e,error:h(t)}}try{return{skillFilePath:e,content:t,parsed:Gp(t)}}catch(t){return{skillFilePath:e,error:p(t)}}}async function Qm(e){const t=await Ci(e);return{...await Xm(e),realSkillFilePath:t}}function Ym(e){return rg(e.data?.environments??e.data?.metadata?.environments)??[]}function eg(e){return rg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function tg(e){return rg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function rg(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 ng(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 og(e){return gi(e,1536)}function sg(e){return!0===e.data?.alwaysApply}function ig(e){return!0===e.data?.["disable-model-invocation"]}function ag({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---`:Vp("",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 ${g(s.length)} characters; the limit is 64. Rename the skill's folder.`),m.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 ${g(i)} characters; the limit is ${g(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${g(a)} tokens; the recommended limit is ${g(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(sg(r))return new w.DX({fullPath:e,content:t,frontmatter:n,type:new w.f5({type:{case:"global",value:new w.i9}}),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),warnings:o});const s="string"==typeof r.data?.description?og(r.data.description):void 0,i=f(s,ig(r));return i?new w.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:tg(r),type:new w.f5({type:{case:"agentFetched",value:new w.Xo}})}):new w.DX({fullPath:e,content:t,frontmatter:n,type:new w.f5({type:{case:"agentFetched",value:new w.Xo({description:s})}}),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),warnings:o})}function cg({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?og(r.data.description):"",o=If(r.data?.paths??r.data?.globs),s=ig(r);return new dm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:f(n,s),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),disableModelInvocation:s})}function lg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new w.DX({fullPath:e,parseError:t,type:new w.f5({type:{case:"agentFetched",value:new w.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new dm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ug(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void lg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});ng(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ag(t)),sg(t.parsed)||e.agentSkills.push(cg(t)))}const dg=(0,fa.debuglog)("cursor-rules-service");function hg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function pg(e){return t=>(dg("%s: %O",e,t),hg())}function fg(e,t){return pm({kind:"agent-store",surface:e,roots:[...t].sort()})}function mg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function gg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new w.i9};else{const r=If(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new w.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new w.Xo({description:og(e.frontmatter.description)})}:{case:"manuallyAttached",value:new w._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 w.DX({fullPath:e.path,content:e.body,type:new w.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class wg{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=zm(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,fa.debuglog)("Failed to load cursor rules from service:",e),[])))));return qm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Gm(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()}),wg.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()}}wg.CHANGE_COALESCE_MS=1e3;class yg{constructor(e,t,r,n,i,a,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Nm(r,t,(0,o.homedir)(),i),this.ignoreService=l??new dl(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Vm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,fa.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,be.q6)(),n=zm(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return yg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Gm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,fa.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return yg.ripwalkCache??=new Wc,yg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(v((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,fa.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{Gm(r)}}isRuleMarkdownFile(e){return v(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Jc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=k(await ac(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else 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{Gm(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=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Jc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([a,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);const f=[...p.values()];return(await async function(e){const t=e.filter((e=>v((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,ir.PH)(t,(e=>async function(e){try{const t=await(0,ti.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await Ci(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=Jm(e.dir)-Jm(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)&&(Km(r.at(-1))||Km(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=>!v((0,s.basename)(e.fullPath))||i.has(e)))}(f.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{Gm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,ti.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ac(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return zm(t,(0,c.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Gm(t)}}toCursorRule(e){return gg({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=zm(r,(0,c.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 l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{zm(n,(0,c.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,ti.stat)(e)).isFile()){const t=b({content:await ac(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{Gm(n)}}async isCursorIgnored(e){try{const t=await ll((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=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=k(await ac(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{Gm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.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{Gm(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=yg.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,s.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,ti.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}}class vg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[]){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.getEnabledSkills=p,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=km(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:Cm(r).dirPath,this.workspaceCatalogKey=pm({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 Nm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const f=performance.now();let m=!1,g=!1,w=!1;const y=this.loadAll(e,l).then((t=>{try{Vm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-f),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:m})}catch{}return t})).catch((e=>(g=!0,pg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=y;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(w=!0,this._loaded!==t?this._loaded:(g&&this.closeSeedWindow(e),void 0===r?y:(m=!0,r)))));this.seededLoaded=t,this._loaded=t,y.then((r=>{this._loaded===t?g?w&&this.closeSeedWindow(e):(this._loaded=y,m&&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(!mm(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]))&&mm(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 fm(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=>w.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>dm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void hm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void dg("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 fm(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=>{dg("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 Im(r,e))t.add(n.dirPath)}for(const r of Rm(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(xm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Em(e,t);return void 0!==r&&2===r.length&&r[0]===_m&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return Sm(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,be.q6)(),n=zm(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Gm(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,ir.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(pg("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&&xm(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=zm(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>mg(o,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>mg(o,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,t))))return void this.reload(n.ctx);const i=this._loaded,a=(async()=>{const e=await i,{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([o]));if(this.isIgnoredSkillPath(o)||this.isPrunedByExtensibilityScan(o))return r;const s=t.get(o);if(void 0===s){try{await(0,ti.stat)(o)}catch{return r}return await this.loadAll(n.ctx)}let a;try{a=await(0,ti.realpath)(o)}catch{return await this.loadAll(n.ctx)}if(a!==s)return await this.loadAll(n.ctx);try{return ug(r,{...await async function(e){const t=await ac(e);return{skillFilePath:e,content:t,parsed:Gp(t)}}(o),realSkillFilePath:a},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(pg("Failed to load Agent Skills at path"));this._loaded=a,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Gm(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,ir.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(fg(this.surface,e),r))}),(e=>{dg("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(fg(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=hg(),r=(await Promise.all(e.map((e=>Zm(e))))).flat().filter((e=>!Sm(e))),n=await Promise.all(r.map((e=>Qm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ug(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=zm(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{dg("Failed to discover nested agent skills: %O",e)}))))),l=new Set(this.getAgentStoreSkillRoots()),u=await Promise.all(this.foldersToWatch.filter((e=>!l.has(e))).map((async e=>{const t=(await Zm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Qm(e))))}))),d=new Set;for(const e of u)for(const t of e)if(!d.has(t.realSkillFilePath))if(d.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),lg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(ng(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ag(t)),sg(t.parsed)||s.push(cg(t))}const h=(await a).flatMap((e=>e?.skills??[])).filter((e=>!Sm(e))),p=await Promise.all(h.map((e=>Ci(e)))),f=[];for(const[e,t]of h.entries()){const r=p[e];d.has(r)||(d.add(r),f.push(t))}const m=await Promise.all(f.map((e=>Qm(e))));for(const e of m)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),lg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(ng(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ag(e)),sg(e.parsed)||s.push(cg(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{Gm(r)}}}function bg(e){let t;switch(e.type){case"global":t=new w.f5({type:{case:"global",value:new w.i9}});break;case"fileGlobbed":t=new w.f5({type:{case:"fileGlobbed",value:new w.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new w.f5({type:{case:"agentFetched",value:new w.Xo({description:og(e.description??"")})}});break;case"manuallyAttached":t=new w.f5({type:{case:"manuallyAttached",value:new w._u}});break;default:e.type,t=new w.f5({type:{case:"manuallyAttached",value:new w._u}})}return new w.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 Sg{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{Vm.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,fa.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,ir.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Vm.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=zm(r,(0,c.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 Zf(e,(e=>e.skills))}(e),a=function(e){return Zf(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(bg(e));for(const t of e){const e=`plugin:${Uu(t.identifier)}`,r=Bu(t.identifier),n=Wu(t.identifier),o=Hu(t.identifier),a=qu(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===Gp(c.content).data?.["disable-model-invocation"]}catch{}i.push(new dm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:og(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{Gm(r)}}}const kg=(0,fa.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()?yn.b$.READONLY:yn.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 Ig(e,t){return await Lm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Rg{constructor(e,t,r="workspace",n=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,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 Ig(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,ti.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await ac(r));if(!o)continue;t.push(new yn.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=Bu(n.identifier),o=Wu(n.identifier),i=Hu(n.identifier),a=qu(n.identifier);for(const c of n.agents){const l=Jf(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?yn.b$.READONLY:yn.b$.DEFAULT;t.push(new yn.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}}var Mg=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const Dg=kl.execFile;function Og(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,_l.D9)(Dg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Mg.w3.UNSPECIFIED,Mg.w3.LEFT,Mg.w3.MIDDLE,Mg.w3.RIGHT,Mg.w3.BACK,Mg.w3.FORWARD,Mg.Dh.UNSPECIFIED,Mg.Dh.UP,Mg.Dh.DOWN,Mg.Dh.LEFT,Mg.Dh.RIGHT;const Fg=(0,fa.promisify)(kl.execFile);function Ng(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 jg(e){const{stdout:t}=await(0,_l.D9)(Fg,"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:Ng(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Mg.w3.UNSPECIFIED,Mg.w3.LEFT,Mg.w3.MIDDLE,Mg.w3.RIGHT,Mg.w3.BACK,Mg.w3.FORWARD,Mg.Dh.UNSPECIFIED,Mg.Dh.UP,Mg.Dh.DOWN,Mg.Dh.LEFT,Mg.Dh.RIGHT;const Lg={pattern:"[\\w-]{1,64}",next:e=>e},Ug={pattern:"[0-9a-f-]{36}",next:()=>Xs.randomUUID()},Bg={pattern:"webp",next:()=>"webp"},Wg={native:[Ug,Bg],agent:[Lg,Ug,Bg],legacyNative:[Ug,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Wg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Lg.pattern}$`),Mg.Z8.NATIVE_X11,Mg.Z8.XDOTOOL,(0,P.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,P.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,P.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,P.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,x.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,P.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Hg=r("../proto/dist/runtime/compact.js");Hg.HL;var qg=(0,Hg.QT)(ar.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);ar.proto3,ar.proto3,ar.proto3,ar.proto3;class zg{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 Gg={left_ptr:qg.ARROW,arrow:qg.ARROW,default:qg.ARROW,top_left_arrow:qg.ARROW,hand:qg.POINTER,hand1:qg.POINTER,hand2:qg.POINTER,pointer:qg.POINTER,pointing_hand:qg.POINTER,xterm:qg.TEXT,ibeam:qg.TEXT,text:qg.TEXT,watch:qg.WAIT,wait:qg.WAIT,progress:qg.WAIT,left_ptr_watch:qg.WAIT,crosshair:qg.CROSSHAIR,cross:qg.CROSSHAIR,tcross:qg.CROSSHAIR,move:qg.MOVE,fleur:qg.MOVE,size_all:qg.MOVE,sb_v_double_arrow:qg.RESIZE_NS,v_double_arrow:qg.RESIZE_NS,ns_resize:qg.RESIZE_NS,row_resize:qg.RESIZE_NS,top_side:qg.RESIZE_NS,bottom_side:qg.RESIZE_NS,sb_h_double_arrow:qg.RESIZE_EW,h_double_arrow:qg.RESIZE_EW,ew_resize:qg.RESIZE_EW,col_resize:qg.RESIZE_EW,left_side:qg.RESIZE_EW,right_side:qg.RESIZE_EW,top_left_corner:qg.RESIZE_NWSE,bottom_right_corner:qg.RESIZE_NWSE,nwse_resize:qg.RESIZE_NWSE,size_fdiag:qg.RESIZE_NWSE,top_right_corner:qg.RESIZE_NESW,bottom_left_corner:qg.RESIZE_NESW,nesw_resize:qg.RESIZE_NESW,size_bdiag:qg.RESIZE_NESW,not_allowed:qg.NOT_ALLOWED,no_drop:qg.NOT_ALLOWED,forbidden:qg.NOT_ALLOWED,circle:qg.NOT_ALLOWED,grab:qg.GRAB,openhand:qg.GRAB,grabbing:qg.GRABBING,closedhand:qg.GRABBING};class Vg{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 zg(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=qg.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 Og("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 Og("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Gg[t]??qg.ARROW}try{const e=await Og("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Gg))if(e.toLowerCase().includes(t))return r}catch{}return qg.ARROW}catch{return qg.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,x.h)("computer-use-lazy");var Kg=r("node:net");function Jg(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 Zg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Xg=Ln.object({rpcSocketPath:Ln.string().min(1).optional(),appControlSocketPath:Ln.string().min(1).optional(),pid:Ln.number().int().positive().optional().catch(void 0),protocolMajor:Ln.number().int().positive().optional().catch(void 0)}).passthrough(),Qg=Ln.object({data:Ln.string(),mimeType:Ln.string().min(1)}).strip(),Yg=Ln.object({message:Ln.string(),screenshot:Qg.optional(),screenshotBefore:Qg.optional(),structuredContent:Ln.unknown().optional(),isError:Ln.boolean()}).strip(),ew=Ln.object({accessibilityTrusted:Ln.boolean(),screenRecordingGranted:Ln.boolean()}).strip(),tw=Ln.union([Ln.object({id:Ln.number().int(),result:Yg,ok:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),sessionId:Ln.string().min(1),ok:Ln.literal(!0).optional(),result:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),ok:Ln.literal(!0),result:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int().nullable().optional(),error:Ln.string().min(1),errorCode:Ln.string().min(1).optional(),result:Ln.never().optional(),ok:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),permissionStatus:ew,result:Ln.never().optional(),ok:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),sessionId:Ln.never().optional()}).strip()]);function rw(e,t){try{return JSON.parse(e)}catch{throw new Zg(`local-cua ${t} is not valid JSON`)}}const nw={responseMaxBytes:33554432,parseServiceState(e){const t=Xg.safeParse(rw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Zg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=tw.safeParse(rw(e.toString("utf8"),"RPC response"));if(!r.success)throw new Zg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Zg("local-cua RPC response ID did not match");return r.data}};class ow extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function sw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Jg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const iw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),aw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class cw{constructor(e){this.mode=e}static isInstalled(){if((0,ni.existsSync)(cw.serviceExecutablePath()))return!0;let e;try{e=nw.parseServiceState((0,ni.readFileSync)(cw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||cw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await cw.readServiceState(),t=e?.pid;return void 0!==t&&cw.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!==cw.protocolMajor&&void 0!==e.pid&&!cw.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;cw.throwIfAborted(e.signal);const t=(0,Xs.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:cw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw cw.rpcError(r);if(void 0===r.sessionId)throw new ow("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 cw.readServiceState();if(void 0===e)return;const r=await cw.sendOnce(cw.socketPathFrom(e),{id:cw.requestID,method:"control/release",requestID:(0,Xs.randomUUID)(),mode:this.mode,sessionId:t},cw.defaultCallTimeoutMs);if(void 0!==r.error)throw cw.rpcError(r)}catch(t){cw.logger.warn(e,"local-cua control release failed",{error:sw(t)})}}}async callTool(e,t,r){cw.throwIfAborted(e.signal);const n=cw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:cw.requestID,method:"tools/call",requestID:(0,Xs.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 cw.rpcError(o,t);const s=o.result;if(void 0===s)throw new ow(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new ow(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=cw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);cw.throwIfAborted(e.signal);try{return await cw.sendOnce(o,t(),n,e.signal)}catch(o){if(!cw.isPreDeliveryConnectionError(o))throw o;cw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:cw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return cw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await cw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new ow(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(cw.throwIfAborted(e.signal),!t){const e=await cw.readServiceState();if(e&&!cw.isExitedIncompatibleHelper(e))return cw.socketPathFrom(e)}await this.launchAndWait(e);const r=await cw.readServiceState();if(!r)throw new ow("local-cua sidecar did not publish service.json after launch");return cw.socketPathFrom(r)}static setLaunchGuard(e){cw.launchGuard=e}async launchAndWait(e){const t=cw.serviceAppPath(),r=cw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){cw.logger.info(e,"launching local-cua sidecar",cw.sidecarLaunchLogFields(t)),"1"===process.env[cw.directLaunchEnv]?await cw.spawnSidecarProcess(e,cw.serviceExecutablePath(),[],{detached:!0}):await cw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+cw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...cw.sharedInstallRelativePath,`${cw.serviceAppBundleName}.app`)}static helperIdentity(){const e=cw.serviceAppPath(),t=process.env[cw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=cw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,ni.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&&aw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??cw.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:iw.get(i.bundleIdentifier))??cw.appSupportFolder)};return(0,ni.existsSync)(a)&&(cw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${cw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,Xs.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[cw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return sw(e)}static socketError(e){const t=sw(e);return new ow(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return cw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,kl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new ow(`local-cua sidecar launch failed: ${cw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{cw.logger.warn(e,"local-cua sidecar process error after launch",{error:cw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,ti.readFile)(cw.serviceStatePath(),"utf8");return nw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Zg)return;throw new ow("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==cw.protocolMajor)throw new ow(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${cw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new ow("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw cw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(cw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Kg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new ow("local-cua RPC aborted"):cw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new ow(`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(cw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>nw.responseMaxBytes)return void d((()=>s(new ow("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=nw.parseResponse({line:n,expectedID:cw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new ow("local-cua RPC connection failed after request delivery")):()=>s(cw.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 ow(e))))})))}))}}let lw;function uw(){if(void 0===lw){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 lw===e&&(lw=void 0),t}));lw=e}return lw}cw.logger=(0,x.h)("local-cua:rpc"),cw.serviceAppBundleName="Cursor Computer Use",cw.appSupportFolder="cursor-computer-use",cw.productionExecutableName="CUCursorService",cw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],cw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",cw.serviceAppOverrideEnv="CUA_SERVICE_APP",cw.directLaunchEnv="CUA_DIRECT_LAUNCH",cw.protocolMajor=1,cw.defaultCallTimeoutMs=45e3,cw.launchReadyTimeoutMs=8e3,cw.launchPollIntervalMs=200,cw.requestID=1;var dw=r("node:module"),hw=r.t(dw,2);const pw="mac-webp-runtime.cjs";function fw(e){return"function"==typeof e}function mw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function gw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(mw):[]}let ww,yw;function vw(){return ww??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=gw()[0]?.getFileName();return function(){const e=hw;if("createRequire"in e&&fw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&fw(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}})(),ww}function bw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(yw??=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 gw()){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,Hp.fileURLToPath)(n):n);r((0,s.join)(t,pw)),r((0,s.join)(t,"..","..","src","computer-use",pw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),pw)),r((0,s.join)(process.cwd(),"src","computer-use",pw)),r((0,s.join)(process.cwd(),"computer-use",pw));try{const e=(0,s.dirname)(vw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",pw)),r((0,s.join)(e,"dist","computer-use",pw))}catch{}for(const t of e)try{const e=vw()(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")}(),yw)}function Sw(...e){return t=["@jsquash","webp",...e].join("/"),vw().resolve(t);var t}async function kw(...e){var t;return await(t=(0,Hp.pathToFileURL)(Sw(...e)).href,bw()(t))}const _w=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Cw=(_w((async()=>{const e=await kw("decode.js");return await e.init({wasmBinary:await ni.promises.readFile(Sw("codec","dec","webp_dec.wasm"))}),e})),_w((async()=>{const[e,t,r]=await Promise.all([kw("utils.js"),kw("meta.js"),kw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await ni.promises.readFile(Sw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Ew="image/png",xw={async normalize(e){if(e.mimeType!==Ew)throw new Error(`Mac screenshot must be ${Ew}, received ${e.mimeType}`);const t=await uw(),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 Cw(),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}},Pw={userFacing:function(e){if(e instanceof ow&&e.userFacing&&e.message.trim().length>0&&!Jg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof ow&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Iw=new Set(["keys"]),Rw=new Set(["matched","mismatch","unchecked"]),Tw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Aw=new Set(["matched"]),$w=new Set(["too_long"]),Mw=new Set(["watched","fell_back","unavailable","over_budget"]);class Dw{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??Pw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Dw.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:Dw.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:Dw.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:Dw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Dw.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:Dw.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===Mg.EB.DOWN||t.value.stroke===Mg.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 Mg.ks({result:{case:"success",value:new Mg.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=Dw.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=Dw.cursorFromResult(e)??Dw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Dw.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",Rw),a=o("unchecked",Tw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Aw.has(i)&&!c||"unchecked"===i&&void 0!==a&&$w.has(a);return new Mg.qA({method:o("method",Iw)??"",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",Mw)})}async errorResult(e){let t;if(Dw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:sw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Dw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:sw(e)})}const r=this.errors.userFacing(e);return new Mg.ks({result:{case:"error",value:new Mg.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 Mg.ks({result:{case:"error",value:new Mg.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Mg.ks({result:{case:"error",value:new Mg.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Dw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Dw.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 xw.normalize(e),failed:!1}}catch(r){const n=sw(r);return Dw.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 Mg.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 Mg.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()}))}}Dw.logger=(0,x.h)("local-cua:actions"),Dw.mouseButtonNames={[Mg.w3.UNSPECIFIED]:"left",[Mg.w3.LEFT]:"left",[Mg.w3.RIGHT]:"right",[Mg.w3.MIDDLE]:"middle",[Mg.w3.BACK]:"left",[Mg.w3.FORWARD]:"left"},Dw.scrollDirectionNames={[Mg.Dh.UNSPECIFIED]:"down",[Mg.Dh.UP]:"up",[Mg.Dh.DOWN]:"down",[Mg.Dh.LEFT]:"left",[Mg.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,x.h)("local-cua:windows");var Ow;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"]),function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Ow||(Ow={}));var Fw=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 Nw{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}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,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Pr.Pi({result:{case:"error",value:new Pr.GU({path:n,error:_i})}});const o=(0,ki.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await fu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Pr.Pi({result:{case:"rejected",value:new Pr.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Pr.Pi({result:{case:"permissionDenied",value:new Pr.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,ti.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,ti.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ki.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),l=await this.pendingDecisionProvider.requestApproval({type:Ow.Delete,details:{path:a},toolCallId:t.toolCallId});if(!l.approved)return new Pr.Pi({result:{case:"rejected",value:new Pr.iq({path:o,reason:l.reason||""})}});let u;try{u=await(0,ti.stat)(o)}catch(e){return"ENOENT"===rl(e)?new Pr.Pi({result:{case:"fileNotFound",value:new Pr.n0({path:o})}}):new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:nl(e)})}})}if(!u.isFile()){const e=u.isDirectory()?"directory":"other";return new Pr.Pi({result:{case:"notFile",value:new Pr.LX({path:o,actualType:e})}})}const d=u.size;let h;if(d<=xi)try{h=await ac(o)}catch{}const p=h??"",f=await(0,ti.stat)(o).catch((()=>{}));if(f?.dev!==u.dev||f.ino!==u.ino)return new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,ti.unlink)(o)}catch(e){return"EACCES"===rl(e)?new Pr.Pi({result:{case:"permissionDenied",value:new Pr.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===rl(e)?new Pr.Pi({result:{case:"fileBusy",value:new Pr.vX({path:o})}}):new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:nl(e)})}})}if(this.fileChangeTracker&&void 0!==h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(o,h,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Pr.Pi({result:{case:"success",value:new Pr.fl({path:o,deletedFile:o,fileSize:BigInt(d),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Fw(r)}}}class jw{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===Lt));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 ps.I0({serverIdentifier:Lt,serverName:Lt,instructions:`User-defined tools for this session (server "${Lt}"). 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 Lw extends jw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Uw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Bw=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 Ww{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,c.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new Uw.uN({result:{case:"success",value:new Uw.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Uw.uN({result:{case:"error",value:new Uw.fk({url:n,error:nl(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Bw(r)}}}class Hw{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){const o=this.changes.get(e);if(o){const t=o.before,s=n||o.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:s};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}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,ti.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 uc(e,t,r,n);await(0,ti.writeFile)(e,o),await lc(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()}}class qw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const zw=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),Gw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],Vw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,Kw=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Jw=new Set(["system","global","command"]),Zw={GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",GIT_SSH_COMMAND:"ssh -o BatchMode=yes",GCM_INTERACTIVE:"Never",GIT_EDITOR:":",GIT_SEQUENCE_EDITOR:":",GIT_OPTIONAL_LOCKS:"0",GIT_LFS_SKIP_SMUDGE:"1",GIT_CONFIG:void 0};function Xw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const Qw=Xw([...yh("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 Yw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function ey(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ty(){const e=new Map;return{async exec(t,r,n){const o=Yw(n);return xh("git",await ry(e,t,r,o),{cwd:t,env:Zw,windowsHide:!0,killSignal:"SIGTERM",timeout:ey(o)})},async run(t,r,n){const o=Yw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Ch(t);return(0,kl.spawn)("git",s,{...o,env:Eh(s,n)})}(0,t,{cwd:e,env:Zw,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"})))}),ey(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 ry(e,t,r,o),o,n?.input)}}}async function ry(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Ch(e),r=kh(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=zw.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=[...Gw,..."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),...Qw],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 xh("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Zw,windowsHide:!0,killSignal:"SIGTERM",timeout:ey(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new qw("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 qw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new qw("read-failed",t)}(e)}if(performance.now()>=r)throw new qw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new qw("read-failed");const r=new Set;for(let e=0;eXw([[`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 ny(e,t,r){return ty().exec(e,t,r)}var oy=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 sy{async exec(e,t,r,n){return iy(e,t,r,n,ny)}forRequest(){const e=ty();return{exec:(t,r,n,o)=>iy(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function iy(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,c.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{oy(s)}}var ay=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class cy{constructor(){this.lineEnd=0,this.nextStart=0}}function ly(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 uy(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 dy=-(2**31),hy=2**31-1;function py(e){return Number.isNaN(e)?0:ehy?hy:e}function fy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return py(Math.trunc(e))}var my=r("../mcp-core/dist/transport/mcp-url-utils.js");function gy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function wy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function yy(e,t,r){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){return!0===e.url?.startsWith("mcp-provider://")}(e))return!0;const n=t.allowedMcpServers??[];return 0===n.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){const n=r?.matchesServerUrlPattern??my.vc;return t.some((t=>{const r=gy(t.command),o=wy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,my.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t,r)}(e,n,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){const n=r?.matchesServerUrlPattern??my.vc;return(t??[]).some((t=>{const r=gy(t.command),o=wy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,my.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t.deniedMcpServers,r)}var vy=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 by extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Sy extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class ky extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class _y{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new by(t);return await o(e,r)}}class Cy{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,c.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new Sy(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{vy(s)}}}class Ey{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,Xs.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,ti.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,ti.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,ti.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var xy=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},Py=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 Iy{async load(e,t,r,n,o){const s=o(e,r);return new Ty(e,t,s,r)}}function Ry(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Ty{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,c.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=xy(t,(0,c.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=xy(s,(0,c.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{Py(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=xy(r,(0,c.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{Py(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=xy(n,(0,c.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{Py(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function Ay(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $y(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 My(e){return e?` (${$y(e,"")})`:""}function Dy(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=Dy(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=Dy(n);if(void 0===e)return;r[t]=e}return r}function Oy(e){const t=Dy(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const Fy=new TextDecoder("utf-8",{fatal:!0});function Ny(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function jy(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=Fy.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=Ny(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: ${$y(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const Ly=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function Uy(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function By(e){if(!Ay(e))return;const t=e.resource;return Ay(t)&&void 0===Uy(t)&&"string"==typeof t.blob&&Ly.has(Ny(t.mimeType))?t.blob:void 0}function Wy(e){const t=e,r=t.resource;if(Ay(r)){const e=Uy(r);return void 0!==e?e:"string"==typeof r.blob?jy(r,r.blob).text:`Resource: ${$y(r.uri,"unknown")}${My(r.name)}`}return t.uri?`Resource: ${$y(t.uri,"unknown")}${My(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function Hy(e){const t=Oy(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var qy=r("zod/v4-mini");const zy=qy.object({CLIENT_ID:qy.string(),CLIENT_SECRET:qy.optional(qy.string()),scopes:qy.optional(qy.array(qy.string()))}),Gy=qy.strictObject({caBundle:qy.string().check(qy.trim(),qy.minLength(1),qy.maxLength(131072))}),Vy=qy.object({type:qy.optional(qy.literal("stdio")),command:qy.string(),args:qy.optional(qy.array(qy.string())),env:qy.optional(qy.record(qy.string(),qy.string())),envFile:qy.optional(qy.string()),cwd:qy.optional(qy.string()),enabledTools:qy.optional(qy.array(qy.string())),startupTimeoutSec:qy.catch(qy.optional(qy.number().check(qy.positive())),void 0)}),Ky=qy.object({type:qy.optional(qy.enum(["http","sse"])),url:qy.string(),headers:qy.optional(qy.record(qy.string(),qy.string())),auth:qy.optional(zy),tls:qy.optional(Gy),placement:qy.optional(qy.enum(["server","client"])),enabledTools:qy.optional(qy.array(qy.string()))}),Jy=qy.union([Vy,Ky]),Zy=qy.object({mcpServers:qy.record(qy.string(),Jy)});Error;const Xy=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Qy(e,t){if("string"==typeof e)return function(e,t){return e.replace(Xy,((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=>Qy(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Qy(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 Yy(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const ev=Yy({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),tv=Yy({caBundle:"ca_bundle"}),rv=Yy({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),nv=Yy({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),ov=(new Map([["auth",{keys:ev,unknownKeyIsError:!1}],["tls",{keys:tv,unknownKeyIsError:!0}]]),"enabled");new Set([...rv.jsonKeyOf.keys(),...nv.jsonKeyOf.keys(),ov]);Symbol("disabled");const sv=(0,x.h)("McpConfig");async function iv(e,t=e=>process.env[e]){try{const r=await(0,ti.readFile)(e,"utf8"),n=Qy((0,Hd.qg)(r),t);return Zy.parse(n)}catch{return{mcpServers:{}}}}async function av(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function cv(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await av(0,t);return n.length>0&&sv.warn((0,be.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 lv=["enterprise","project","user","env"];function uv(e){return"project"===e||"env"===e}const dv=["0.0.0.0/0","::/0"];function hv(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,my.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function pv(e){const t=!0===e.enabled,r=hv(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...dv];const t=hv(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...dv]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...dv];const r=(0,my.b6)(e);return r.includes("*")?[...dv]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class fv 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 mv=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class gv extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class wv 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 yv(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function vv(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&&mv.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(!yv(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 wv;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 wv;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 gv;return e(i,a)}}function bv(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)&&Rv(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=_v(e,n),s=Pv(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:_v(e,"cause"),l=Pv(c,t,r),u=e instanceof AggregateError?_v(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>Pv(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])=>kv(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(Ev(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[Cv];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=$v(e);return void 0!==g&&$v(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 Sv(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 kv(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function _v(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const Cv=Symbol.for("nodejs.util.inspect.custom");function Ev(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 xv(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return bv(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>xv(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:xv(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function Pv(e,t,r){if(e instanceof Error)return bv(e,t,r);try{return Rv(e,t)?xv(e,t,1,r):e}catch{return}}const Iv=4096;function Rv(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=Iv||n.length>Iv)return Tv(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((Av(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(_v(s,"message"),_v(s,"stack"),_v(s,"cause")),s instanceof AggregateError&&n.push(_v(s,"errors")));for(const e of Object.keys(s))n.push(_v(s,e))}}return!1}function Tv(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,_v(n,e)]))),message:_v(n,"message"),stack:_v(n,"stack"),cause:_v(n,"cause"),...n instanceof AggregateError?{errors:_v(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function Av(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 $v(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const Mv=/spt_[A-Za-z0-9_]{6,}/g,Dv=/[A-Z0-9]/;function Ov(e){return function(e){return e.replace(Mv,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&Dv.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var Fv=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set([1,2]);const Nv="cursor/requiresConfirmation",jv="https://grok.com/connectors-oauth-exchange-code/",Lv="https://x.com/i/connectors/oauth_callback",Uv="https://chat.x.com/connectors/oauth_callback",Bv="https://lite.x.com/i/connectors/oauth_callback",Wv={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},Hv={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[jv,Lv]},qv="x-cursor-auth";function zv(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 Gv="https://mcp.shop.com",Vv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Kv=new Map([["mcp.slack.com",{gate:"mcp_oauth_scope_step_up",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/}]]),Jv=new Map([["gmailmcp.googleapis.com",{...Wv,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",{...Wv,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Wv,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",{...Wv,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Wv,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Wv,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Wv,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",Hv],["mcp.money-staging.x.com",Hv],["mcp.money.x.com",Hv],["connectors-gateway.grok.gcp.mouseion.dev",Vv],["connectors-gateway.grok.com",Vv],["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.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","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:Gv}}]]),Zv=[".cloud.databricks.com",".azuredatabricks.net",".gcp.databricks.com"];const Xv=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Qv={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Yv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0};function eb(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(".."))&&Zv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Qv:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Xv.test(e.pathname.replace(/\/+$/,""))}(t)?Yv:(r=t.hostname,Jv.get(r.toLowerCase()));var r}function tb(e){return e.endsWith("/")?e:`${e}/`}async function rb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!tb(r.pathname).startsWith(tb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const nb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function ob(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function sb(e,t){if(void 0===t)return;const r=new URL(e),n=ob(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!nb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function ib(e){const t=ob(e);return void 0===t?void 0:Kv.get(t.hostname.toLowerCase())}const ab=new Set([...Jv].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),cb="https://www.cursor.com/bot/mcp/oauth/callback",lb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:cb},ub="tailnet_";new Set([`${ub}waiting_for_approval`,`${ub}tailnet_locked`,`${ub}joining`]);const db="grokbot://mcp/oauth/callback",hb="http://localhost:8787/callback",pb="gb";new Set(["outlook","outlook-calendar","onedrive","teams"]),new Set(["teams"]);function fb(e){const t=new URL(hb);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 gb(e){const t=e.redirectUrl??hb;if(!0!==e.loopbackIpv4||!mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function wb(e,t=lb){const r=new Set,n=void 0!==e&&mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===db&&r.add(t.grokBotBounce),r.add(hb),e&&n&&r.add(e),Array.from(r)}new Map([[pb,db],["gw",jv],["gd",hb],["xa",Lv],["xc",Uv],["xl",Bv],...[18787,28787,31787].map((e=>[`gd${e}`,fb(e)]))]),new Map([[db,pb],[cb,pb],[jv,"gw"],[Lv,"xa"],[Uv,"xc"],[Bv,"xl"]]),gb({loopbackIpv4:!0}),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const yb=new Set([429,502,503,504]);function vb(e){return"object"==typeof e&&null!==e}function bb(e){const t=vb(e)?e.code:void 0,r=(e instanceof Error||vb(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&&yb.has(o)&&!yb.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}const Sb=8192;function kb(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==zv(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const _b=/\$\{[^}]*\}/;function Cb(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&_b.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const Eb=new Map;async function xb(e,t=fetch){if(void 0===zv(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=Eb.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 Eb.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Pi.J)((function(){Eb.clear()}));const Pb={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function Ib(e){return Pb}const Rb=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Tb=["invalid_request","invalid_token","insufficient_scope"];function Ab(e){return Tb.some((t=>t===e))}function $b(e){const t=[];for(const r of e){if(t.length>=20)break;r.length>0&&r.length<=200&&Rb.test(r)&&!t.includes(r)&&t.push(r)}return t}const Mb=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,Db=/"((?:[^"\\]|\\.)*)"?/y,Ob=/[^\s,]*/y;function Fb(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 Lb(e){if("object"!=typeof e||null===e||Array.isArray(e))return Nb;const t=jb("grantedScopes"in e?e.grantedScopes:void 0),r=jb("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:jb("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:jb("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ub(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function Bb(e,t){return e.filter((e=>!t.has(e)))}const Wb={stepUpScopes:[],recordRequestedScopes:async()=>{}};function Hb(e){const t=ib(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=Ib(e.accountKey);let o;const s=async()=>Lb(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ub(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=Fb(t,"error")?.toLowerCase(),n=Fb(t,"resource_metadata");return{error:void 0===r||""===r?"none":Ab(r)?r:"other",scopes:$b((Fb(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 ab.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl)||!await e.isEnabled())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 $b(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(){if(!await e.isEnabled())return Wb;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:Ub(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Lb(n),s=Ub(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=Bb(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:Bb(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}=Lb(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function qb(e){const t=ib(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function zb(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:qb(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 Gb extends Error{constructor(e,t,r){super(zb({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 zb({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Vb(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}}var Kb=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Jb="2026-07-28",Zb=-32022,Xb="io.modelcontextprotocol/protocolVersion",Qb="io.modelcontextprotocol/clientCapabilities",Yb="io.modelcontextprotocol/clientInfo",eS="io.modelcontextprotocol/serverInfo",tS={name:"cursor",version:"1.0.0"},rS=new Map;function nS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oS(e){const t=new URL(String(e));return t.hash="",t.href}function sS(e,t){const r=rS.get(e);return!(void 0===r||r<=t()&&(rS.delete(e),1))}function iS(e,t){try{return oS(e)===t}catch{return!1}}function aS(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}function cS(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Jb),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=nS(o.params)?o.params:{},a=nS(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===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,[Xb]:Jb,[Qb]:n.capabilities,[Yb]:n.clientInfo}}});return{...e,headers:s,body:l}}function lS(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function uS(e,t){const r=oS(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...tS}},s=!1;const i=()=>s||sS(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,cS(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!aS(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!nS(n)||!nS(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Jb))return lS({id:t,error:{code:Zb,message:"Unsupported protocol version",data:{requested:Jb,supported:s??[]}}});const i=nS(o._meta)?o._meta:{},a=nS(i[eS])?i[eS]:{name:new URL(r).hostname,version:"unknown"};return lS({id:t,result:{protocolVersion:Kb.aE,capabilities:nS(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){rS.set(e,t()+6e5)}(r,n)),d}return e(i,cS(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!iS(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!nS(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()&&iS(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=nS(l.message.params)?l.message.params:{};o={capabilities:nS(e.capabilities)?e.capabilities:{},clientInfo:nS(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?sS(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||!aS(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(!nS(r)||!nS(r.error))return!1;const n=r.error;if(n.code!==Zb||!nS(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Jb)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function dS(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()===qv));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()!==qv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function hS(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(qv,i),r(n,{...o,headers:a,redirect:"manual"})}}class pS{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=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var fS=r("crypto");function mS(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function gS(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 wS(e,t){return gS(e,t)}function yS(e){if(e)return(0,fS.createHash)("sha256").update(e).digest("hex").slice(0,12)}function vS(e){if(e&&0!==e.length)return yS(JSON.stringify([...e].sort()))}function bS(e){return{clientIdHash:yS(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:vS(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function SS(e){return"object"==typeof e&&null!==e}function kS(e,t){let r=e;for(const e of t){if(!SS(r)||!(e in r))return;r=r[e]}return r}function _S(e,t){for(const r of t){const t=kS(e,r.split("."));if("string"==typeof t)return t}}function CS(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function ES(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 xS=e=>e;function PS(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?DS(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?DS(t(r)):void 0}}function IS(e){if(e&&"object"==typeof e)return SS(e)?e.cause:void 0}function RS(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const TS="[REDACTED]",AS=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function $S(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${TS}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${TS}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${TS}`)}function MS(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function DS(e,t){return MS($S(e),t?.maxLength)}function OS(e,t=xS){if("string"==typeof e)return MS($S(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")||AS.test(t)}(e)?TS:"string"==typeof r?$S(t(r)):r));if(!r)return;return MS(r)}catch{return}}function FS(e,t=xS){const r=IS(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=PS(r,t),i=PS(e,t)??s,a=_S(e,["code","cause.code"]),c=CS(e)??CS(r)??_S(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:DS(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=kS(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??ES(i)??ES(s),d=OS(kS(e,["response","body"])??kS(e,["body"])??kS(e,["data"])??kS(e,["cause","body"])??kS(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 mS({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:RS(e,t),sdkErrorKind:p})}const NS={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 jS(e){const t=e.message??NS[e.event],r={event:e.event,cursorMcp:{oauth:mS({...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 LS=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]))),US=4096;function BS(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function WS(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function HS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qS(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(HS(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function zS(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function GS(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function VS(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:GS(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:GS(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:GS(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:GS(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:GS(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:GS(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:GS(t.get("content-length"))}}function KS(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 JS(e){const{input:t,init:r}=e,n=gS(WS(t)),o=function(e,t){const r=new Headers(qS(BS(e)?e.headers:void 0));return new Headers(qS(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=zS(o),i=o.get("content-type"),a=yS(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return LS.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(BS(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:VS(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function ZS(e,t){const r=zS(e.headers),n=GS(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:yS(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:yS(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:XS(e.headers,"retry-after"),slackRateLimitType:XS(e.headers,"x-slack-ratelimit-type")}}function XS(e,t){return e.get(t)?.slice(0,64)??null}function QS(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 YS(e,t){const r=JS({input:e,init:t});if(void 0!==KS(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 ek=e=>e;async function tk(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function rk(e){if(!YS(e.input,e.init))return;const t=await tk(e.response,US,e.redact);if(void 0!==t)try{return OS(JSON.parse(t))}catch{return DS(t,{maxLength:US})}}async function nk(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 tk(t,US,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=gS(WS(e.input)).path)&&!0!==t?.endsWith("/mcp"))return DS(e.rawText,{maxLength:US});var t;try{const t=JSON.parse(e.rawText);return HS(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!HS(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?DS(r.message,{maxLength:US}):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 rk({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ok(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function sk(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=>sk(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,sk(n,t,r+1)])))}function ik(e,t){const r=e=>{const r=sk(e,t,0);return HS(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 ak(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:ik(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await nk({input:s,init:i,response:e,redact:n??ek});return!r&&e.ok||ok((()=>{!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=JS({input:t,init:r}),l=KS(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:ZS(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")&&!YS(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:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!SS(e))return;const t=SS(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}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await nk({input:s,init:i,response:t,redact:n??ek}):{};throw ok((()=>{!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=FS(n,e.redactLogText),u=JS({input:t,init:r}),d=KS(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?ZS(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:QS(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}Error,Error;const ck=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),lk=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),uk=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];function dk(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}}const hk=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],pk=[".exe",".cmd",".bat"],fk=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,mk=new Set(["py","pyw"]),gk=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),wk=new Set;function yk(e){return hk.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 vk(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of pk)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(fk.test(r)||mk.has(r)||"uvx"===r)return!0;if("uv"===r){const e=vk(t,gk);return"run"===e?.value||"tool"===e?.value&&"run"===vk(e.rest,gk)?.value}return"pipx"===r&&"run"===vk(t,wk)?.value}(n,o)?yk(i)||yk(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function Sk(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 kk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),_k=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Ck=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Ek=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),xk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");function Pk(e){return`${typeof e}:${String(e)}`}function Ik(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(Pk(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Pk(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=Pk(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 Rk(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,Xs.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Tk{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,Kb.vo)(e)&&(0,Kb.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Kb.wU)(e)||await this.inner.send(e,t)}}const Ak=Ln.object({tools:Ln.array(Ln.unknown()),nextCursor:Ln.unknown().optional()}),$k={typeFilled:0,toolDropped:0,outputStripped:0};function Mk(e){if(Lk(e))return"string"==typeof e.name?e.name:void 0}function Dk(e){return Ok(e.issues.filter((e=>"outputSchema"===e.path[0])))}function Ok(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function Fk(e){if(!Lk(e))return e;const t={...e};return delete t.outputSchema,t}function Nk(e){return Lk(e)&&!("type"in e)}function jk(e,t){return{...e,inputSchema:{type:"object",...t}}}function Lk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Uk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const Bk=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Uk.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,Xs.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 Wk{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>=Sb}append(e){const t=Sb-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}=bi(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:kb(t),...r}))}catch{}}const Jk=(0,P.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 Zk(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Xk=["authorization_code","refresh_token"],Qk=["code"];class Yk{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=ob(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(Gv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?sb:rb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled??(()=>!1),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,Xs.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=()=>!1){const n=eb(e);if(!0!==n?.pinsScopesOverConfiguredScopes){if(void 0!==t&&t.length>0)return t;const n=ib(e);return void 0!==n&&r(n.gate)?n.baseScopes:t}return void 0===n.scopesPinGate||r(n.scopesPinGate)?n.scopes??t:t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=eb(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 e_(e){const{serverName:t,config:n,tokenStorage:o}=e,{isScopeChallengeStepUpEnabled:s}=e,i=await xb(n.url,e.fetchImpl),a=gb({loopbackIpv4:i?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),c=function(e,t){const r=Cb(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:wb(t),grant_types:[...Xk],response_types:[...Qk],token_endpoint_auth_method:"none"}}(n.auth,a),l=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:c});return new Yk({identifier:t,redirectUrl:a,serverUrl:n.url,restMcpProviderMetadata:i,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:wb(a),token_endpoint_auth_method:"none",grant_types:[...Xk],response_types:[...Qk],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...void 0!==s&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Hb({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),isEnabled:async()=>s(),readScopesSupported:t=>async function(e){try{const{discoverOAuthProtectedResourceMetadata:t}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"));return(await t(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch)).scopes_supported}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:l,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:l?.client_id})})}const t_=new Set;let r_=!1;function n_(){for(const e of t_)try{process.kill(e,"SIGKILL")}catch{}}function o_(e,t){return uS(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function s_(e,t,r){const n=dS(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?hS((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class i_{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 pS,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}})();jS({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(){return new _k.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}},extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}},jsonSchemaValidator:Bk})}setupElicitationHandler(){this.client.setRequestHandler(Kb.$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){const d=new URL(t.url);o=o??hb;const h=await e_({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,isScopeChallengeStepUpEnabled:u}),p=h.tokens(),f=dS(t.url,n),m=f.headers,g=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),w=void 0!==f.cursorAuthHeaderValue&&void 0!==f.cursorAuthOrigin&&void 0!==g?hS((()=>f.cursorAuthHeaderValue),f.cursorAuthOrigin,g):g,y=e=>void 0===w||void 0===i?w:ak({fetch:w,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let v;const b=e=>{const r=h.scopeStepUp,n=e??g;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,kk.j2)(h,{serverUrl:d.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==w?{fetchFn:w}:{}});const r=h.lastRedirectUrl;v=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:Vb(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){Ib(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 Gb(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},S=i_.createClient(),k=e=>e instanceof kk.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&ck.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!lk.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&&uk.some((e=>e.test(n)))}(e)}(e),_=async t=>{if(!h.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!==v&&v.redirectUrl===h.lastRedirectUrl?v.resourceMetadataUrl:void 0;await(0,kk.j2)(h,{serverUrl:d.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==w?{fetchFn:w}:{}}),a&&jS({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...wS(d.toString()),...dk(h.tokens(),{expiresInIsFresh:!0})}})},C=r=>{const n=h.lastRedirectUrl?.toString?.()??"",o=new i_(e,S,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await _(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:h,authCodeExchange:_,sessionId:r,config:t});return o},E=async()=>{const r=new Ck.A(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(y("sse"))});try{return await S.connect(r),new i_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await r.close().catch((()=>{})),k(t))return a&&jS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(p?.refresh_token),...wS(d.toString()),...FS(t,i?.redactLogText)}}),C();throw t}};if("sse"===t.type)return E();const x=new xk.j(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(o_(y("streamableHttp"),d))});try{await S.connect(x);const r=function(e,t=Date.now){return sS(oS(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:Rk({url:t.url,headers:n,accessToken:h.tokens()?.access_token})}}(S,x);return new i_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,sessionId:x.sessionId,protocolVersion:x.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(k(t))return a&&jS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(p?.refresh_token),...wS(d.toString()),...FS(t,i?.redactLogText)}}),C(x.sessionId);if(function(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)}(t))return E();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=i_.createClient(),o=new xk.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new i_(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=hb,i,a,c,l,u){const d=new URL(t.url),h=await e_({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=s_(t.url,o,i),m=new xk.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ak({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=i_.createClient();return await g.connect(m),new i_(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=hb,i,a,c,l){const u=await e_({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(Rk({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=s_(t.url,o,i),p=new xk.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=i_.createClient();return await f.connect(new Tk(p,r.result)),new i_(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 xk.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{qk(s,(0,c.VI)(e.withName("McpSdkClient.fromCommand")),!1);const u=(l=o?.spawn,void 0!==l||"linux"!==process.platform?l:(e,t,r)=>(0,_l.D9)(kl.spawn,e,t,r)),d=r.args??[],h=new Ek.oQ({command:r.command,args:d,env:bk({command:r.command,args:d,env:n}),cwd:r.cwd,stderr:"pipe",...u&&{spawn:u}}),p=function(e){const t=new Wk;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>DS(t.text.replace(/\s+/g," ").trim(),{maxLength:Sb}),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)}))}}}(h.stderr),f=i_.createClient(),m=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let g;h.onclose=()=>{var e;void 0!==g&&(e=g,t_.delete(e))};const w=new AbortController,y=f.connect(h,{timeout:m,signal:w.signal});let v;g=h.pid??void 0,void 0!==g&&(i=g,t_.add(i),r_||(r_=!0,process.on("exit",n_)));const b=new Promise(((e,r)=>{v=setTimeout((()=>r(new Error(`MCP server connection timed out after ${m}ms: ${t}`))),m)}));try{await Promise.race([y,b])}catch(e){throw w.abort(),y.catch((()=>{})),await h.close().catch((()=>{})),await p.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Hk.set(r,t),r}(e,p.read())}finally{void 0!==v&&clearTimeout(v)}return new i_(t,f,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==g,serverSignals:Ik(h)})}catch(e){s.error=e,s.hasError=!0}finally{zk(s)}var i,a,l}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 xk.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,ir.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof ir.MU?{outcome:"timeout",durationMs:t}:e instanceof xk.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=qk(t,(0,c.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Zk(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()=>{const e=await Sk({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...$k}}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}},Ak),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(Lk(e)){const r=e.inputSchema;Nk(r)&&(t=jk(e,r),s++)}let n=Kb.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Kb.Dn.safeParse(Fk(t));o.success&&(a++,r(Mk(e),Dk(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Mk(e),Ok(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(c_.has(n))return c_.delete(n),c_.add(n),!1;if(c_.add(n),c_.size>256){const e=c_.keys().next().value;void 0!==e&&c_.delete(e)}return!0})(n,this.serverName,e??"")&&Gk.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+=t.typeFilled,l_(r.ctx,"type_filled",t.typeFilled),l_(r.ctx,"tool_dropped",t.toolDropped),l_(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:Dy(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:Dy(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){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,e,n),e instanceof kk.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const t=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(t,this.stateValue,"runtime_unauthorized",{...FS(e,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}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=Kb.O4.MethodNotFound;if(t instanceof Kb.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof kk.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Kb.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof xk.b||e instanceof Ck._){const t=e instanceof xk.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&&Gk.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=qk(s,(0,c.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",Zk(this.config));const l=this._callToolLock,u=this._callToolQueueDepth;let d;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{d=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=qk(e,(0,c.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",u);const r=performance.now();await l;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",u)}catch(t){e.error=t,e.hasError=!0}finally{zk(e)}}if("requires_authentication"===this.stateValue.kind)throw new kk.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const d=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=qk(n,(0,c.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const l=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===l.isError),Kk(e,this.config,{isError:!0===l.isError}),{content:l.content,isError:!0===l.isError,structuredContent:(i=l.structuredContent,Oy(i)),_meta:Hy(l._meta)}}catch(e){n.error=e,n.hasError=!0}finally{zk(n)}}catch(t){t instanceof Gb?(Kk(e,this.config,{error:t,httpStatus:t.decision.status}),function(e,t){try{Jk.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,t)):Kk(e,this.config,{error:t});const r=t instanceof Gb&&"offer"===t.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==d;if((t instanceof kk.D_||r)&&"ready"===this.stateValue.kind){const e=this.stateValue,n=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:n,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,r?"scope_step_up":"runtime_unauthorized",{...FS(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,l.then(d)}}catch(e){s.error=e,s.hasError=!0}finally{zk(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},Kb.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(qk(t,(0,c.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{zk(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(qk(t,(0,c.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 Sk({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{zk(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return qk(r,(0,c.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{zk(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return qk(t,(0,c.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await Sk({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{zk(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return qk(n,(0,c.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{zk(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 a_=(0,P.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),c_=new Set;function l_(e,t,r){if(0!==r)try{a_.increment(e,r,{outcome:t})}catch{}}class u_ 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 d_{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new Yt(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class h_{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new d_({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class p_{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=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{zk(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 f_{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=qk(t,(0,c.VI)(e.withName("McpManager.getToolSet")),!1),n=qk(t,m_(this.listingDeadlineAt),!1),o=await(0,ir.PH)(Object.entries(this.clients),(([e,t])=>n.within(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},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 d_(a)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("McpManager.getInstructions")),!1),n=qk(t,m_(this.listingDeadlineAt),!1),o=await(0,ir.PH)(Object.entries(this.clients),(([e,t])=>n.within(t.getInstructions(r.ctx)).then((e=>e&&0!==e.trim().length?new ps.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{zk(t)}}}function m_(e){if(void 0===e)return{concurrency:4,within:e=>e,[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:e=>Promise.race([e,r]),[Symbol.dispose]:()=>clearTimeout(t)}}function g_(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 w_{constructor(e){this.options=e,jS({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:wS(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return jS({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...dk(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),jS({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...dk(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){jS({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){jS({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...FS(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return jS({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...bS(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),jS({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...bS(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(jS({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 y_{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 v_{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 b_=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},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 k_=(0,x.h)("DefinitionMcpLoader");function __(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 C_(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function E_(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function x_(e){return e?.length??0}function P_(e){if(void 0!==e)return(0,Xs.createHash)("sha256").update(pv(e)).digest("hex")}function I_(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?Ov(r):r)}async function R_(e,t,n,o,s={middlewares:[],configPath:""},i,a,l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=b_(u,(0,c.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);let f=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=b_(s,(0,c.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(E_);return await async function(e,t,n,o){const s=n.cwd?__({filePath:n.cwd}):void 0;let i,a;if(n.args&&n.args.length>0)i=__({filePath:n.command,baseDir:s}),a=n.args.map((e=>__({filePath:e,baseDir:s})));else{const e=(0,Fv.A)(n.command);i=__({filePath:e[0],baseDir:s}),a=e.slice(1).map((e=>__({filePath:e,baseDir:s})))}const c=n.env??{},{startupTimeoutSec:l}=n,u=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),d=(0,my.$H)(u);if(void 0!==d){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:h}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),p=s??process.cwd(),f=await n(d,p);k_.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=${x_(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${x_(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${x_(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${P_(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:x_(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:x_(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:x_(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:P_(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}));try{return await i_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c,{spawn:(e,t,r)=>h(e,t,r,f)})}catch(e){if(e instanceof o)throw new fv(t,e);throw e}}return!0===u?.enabled&&"no_sandbox"===u.mcpNetworkMode&&(!0===u.win32UserExtensionUnsandbox?k_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):k_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),i_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c)}(h,t,n,e)}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){const c=g_(e,k_),l=function(e,t,r){return{logger:{debug:(t,r)=>k_.debug(e,t,r),info:(t,r)=>k_.info(e,t,r),warn:(t,r)=>k_.warn(e,t,r),error:(t,r,n)=>k_.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:I_(r)}}(e,t,a),u=void 0!==s&&yv(r.url)?vv(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return i_.fromStreamableHttp(t,r,n,r.headers,o,u,l,c,void 0,void 0,i)}(h,t,n,o,e,d.find(C_),a,l.isLinkSharedPaymentTokenLogRedactionEnabled)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{S_(s)}};for(const e of d){const r=f;f=async(n,o)=>await e.load(n,t,o,h,r)}try{return await f(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=Hk.get(e);void 0!==r&&Hk.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=bv(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 A_{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{b_(r,(0,c.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,ir.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=I_(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Hk.get(e)}(r);k_.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 f_(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{S_(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(E_);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,pv(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(k_.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,ir.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{b_(n,(0,c.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{S_(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new y_(this.tokenStorage,n),s=g_(e,k_),i=new w_({inner:o,logger:s,redactLogText:I_(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new v_(i):i;return R_(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.isScopeChallengeStepUpEnabled,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){k_.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 by||e instanceof Sy||e instanceof ky||e instanceof $_}(r)}}class $_ 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 M_=[1e3,3e3];class D_{constructor(e){this.blockingService=e}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={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked)throw new $_(t,i.reason??"teamPolicy",i.message);for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),t}catch(e){if(e instanceof gv)throw new $_(t,"teamPolicy",e.message);const r=e instanceof wv?M_[n]:void 0;if(void 0===r)throw e;await(0,ir.cb)(r)}}}class O_ extends A_{constructor(e,t,r=[],n={}){super(new T_(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new O_(t,e,r)}}function F_(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 N_=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function j_(e){const t=N_.VE.safeParse(e);return t.success?t.data:void 0}function L_(e){const t=N_.H5.safeParse(e);return t.success?t.data:void 0}class U_{constructor(e){this.mcpAuthPath=e;const t=U_.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,U_.mcpAuthPromises.set(e,t),t.catch((()=>{U_.mcpAuthPromises.get(e)===t&&U_.mcpAuthPromises.delete(e)}))}U_.saveLocks.has(e)||U_.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,ti.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=j_(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?j_(n.tokens):void 0,clientInfo:"clientInfo"in n?L_(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=U_.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;U_.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.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,ti.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}U_.mcpAuthPromises=new Map,U_.saveLocks=new Map;const B_=Buffer.from([137,80,78,71,13,10,26,10]),W_=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),H_=e=>{if(e.lengthe.subarray(e.length-W_.length).equals(W_)||(e=>{let t=B_.length+25;for(;t+W_.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-W_.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+W_.length).equals(W_);t+=W_.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)}},q_=e=>1===e||e>=208&&e<=216,z_=e=>192===e||193===e||194===e,G_=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,V_=e=>0===e||e>=208&&e<=215,K_=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=H_(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(q_(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=K_(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(q_(r)){t+=2;continue}if(218===r||217===r||G_(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(z_(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),Z_=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),X_=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,B_.length).equals(B_)?"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},Y_={0:1,2:3,4:2,6:4},eC=({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}`)}}},tC=({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)},nC={0:1,2:3,3:1,4:2,6:4},oC=[1,2,4,8,16],sC=[[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]],iC=async e=>{const t=aC(e);if(void 0===t)return;const r=cC(t);let n=0;const o=sh.Readable.from(t.idat).pipe((0,ah.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`)},aC=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=nC[i[9]];if(void 0===e||!oC.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}},cC=({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?sC.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const lC=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},uC=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),dC=e=>{if(!uC(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)}}},hC=e=>lC().decode(e),pC=e=>lC().encode(e);async function fC(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);J_(e.data);return e.resizeWithoutBudget(e.data)}const mC=[{width:1280,height:800},{width:1456,height:840}],gC=1048576,wC=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function yC(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 vC=(e,t,r=1024)=>yC(e,t,r),bC=(e,t,r)=>{e.resize({w:t,h:r})},SC=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`)},kC=(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:SC(((e,t)=>{switch(t){case"png":return(e=>{let t,r=B_.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Z_(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))}};const _C=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return fC({data:e,budgetBytes:r,maxImageBytes:gC,fitImage:yC,resizeWithoutBudget:e=>_C(e,n)})}if(uC(e))return(async(e,t)=>{const r=dC(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:wC(e),mimeType:"image/webp"};const n=void 0!==r&&mC.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!vC(r.width,r.height,1280).needsResize)&&e.length<=gC)return{data:wC(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:wC(e),mimeType:"image/webp"};SC(r);const o=await hC(e),s=(await uw()).fromBitmap({data:Buffer.from(o.data),width:o.width,height:o.height});let{width:i,height:a,needsResize:c}=n?{width:s.bitmap.width,height:s.bitmap.height,needsResize:!1}:vC(s.bitmap.width,s.bitmap.height,1280);c&&bC(s,i,a);let l=await pC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});for(;l.length>gC&&i>8&&a>8;)i=Math.max(8,Math.round(.8*i)),a=Math.max(8,Math.round(.8*a)),bC(s,i,a),l=await pC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});return{data:wC(l),mimeType:"image/webp",reencoded:!0}})(e,t);const r=J_(e);if(void 0!==r&&e.length<=gC&&!vC(r.width,r.height).needsResize)return{data:wC(e),mimeType:r.mimeType};const n=Q_(e);void 0!==n&&kC(e,n),"png"===n&&await iC(e);const o=await uw(),s=void 0===r?void 0:vC(r.width,r.height),i="image/png"===r?.mimeType&&!0===s?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(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=Y_[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}})(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{})):void 0,a=void 0===i?await o.read(e):o.fromBitmap(i),c=(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"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=vC(a.width,a.height);if(void 0===i&&!h&&e.length<=gC&&l===c)return{data:wC(e),mimeType:c};let p=u,f=d;h&&bC(a,p,f);let m=await a.getBuffer(l);for(;m.length>gC&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),bC(a,p,f),m=await a.getBuffer(l);return{data:wC(m),mimeType:l,reencoded:!0}},CC=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Q_(t);let n;if(uC(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{kC(t,r);const e=await uw();n=async()=>("png"===r&&await iC(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}};function EC(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 xC(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=gi(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?.[Nv]}(e)&&(t[Nv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}var PC=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},IC=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 RC=(0,P.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),TC=(0,P.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),AC=(0,P.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),$C=(0,P.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),MC=(0,P.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"]}),DC=(0,P.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"]}),OC=(0,x.h)("McpFileSystemWriter"),FC="mcpFsStructuredLogOptIn";function NC(e,t){return t?.includeStructuredLogs?{...e??{},[FC]:!0}:e}const jC={debug(e,t,r,n){OC.debug(e,t,NC(r,n))},info(e,t,r,n){OC.info(e,t,NC(r,n))},warn(e,t,r,n){OC.warn(e,t,NC(r,n))},error(e,t,r,n,o){OC.error(e,t,r,NC(n,o))}},LC="mcps",UC="tools",BC="~staging",WC="~prev",HC="mcp_auth",qC="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.",zC="# >>> CURSOR MANAGED BLOCK >>>",GC="# <<< CURSOR MANAGED BLOCK <<<",VC=["# 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 KC(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function JC(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ZC(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function XC(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 QC(e){if(Array.isArray(e))return e.map((e=>QC(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,QC(t)]));return Object.fromEntries(t)}return e}function YC(e){return JSON.stringify(QC(e))}function eE(e){const t=e.map((e=>({value:e,key:YC(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function tE(e){const t=eE(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=eE(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=eE(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return YC({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 rE{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=>{jC.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),jC.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=`${zC}\n${VC}\n${GC}\n`;let n;await(0,ti.mkdir)(e,{recursive:!0});try{n=await(0,ti.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==rl(e))throw e}if(void 0===n)return void await(0,ti.writeFile)(t,r);const o=n.indexOf(zC),i=n.indexOf(GC,o+30);if(-1===o||-1===i)await(0,ti.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,ti.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{jC.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,LC);try{const e=await(0,ti.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(BC))).map((e=>(0,ti.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==rl(e)&&jC.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:Gt(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Gt(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){jC.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,be.q6)();return e&&(t=t.with(x._O,e)),t}getLogContext(e){return e.with(x._O,this.ctx.get(x._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return ZC(this.mcpAuthCopyOverrides?.authToolDescription)??qC}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Bt(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return ZC(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=ZC(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:HC},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Bt(e)?this.getNeedsAuthStatusMessage(e):ZC(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){jC.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${nl(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(jC.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 KC(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||jC.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?KC(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?KC(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?KC(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:XC(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=dE(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,LC,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=dE(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,LC,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===HC))||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:HC,name:HC,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)?jC.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):jC.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===HC))){const t=e.tools.find((e=>e.toolName===HC));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??[])];jC.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=>(jC.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 jC.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${nl(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=>{jC.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):jC.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)),jC.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=dE(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{PC(r,(0,c.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Gt(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=>(jC.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(jC.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);jC.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){jC.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{IC(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,UC,`${JC(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{PC(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,LC);await(0,ti.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,tE(e))}catch(t){jC.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&jC.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,ti.stat)((0,s.join)(i,e.sanitizedId))}catch{jC.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??dE(e);r.has(n)?(jC.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(jC.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}const d=void 0===this.cachedServerData;if(d)try{const e=await(0,ti.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(BC)&&!e.endsWith(WC))));for(const r of e)if(r.endsWith(BC))await(0,ti.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else if(r.endsWith(WC)){const e=r.slice(0,-5);if(t.has(e))await(0,ti.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,ti.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,ti.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 u.add(e)}catch(e){jC.error(o,"Error clearing mcps directory",e)}const h=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));jC.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:h,unchangedServerCount:t.length-l.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:d,projectDirHash:(0,Xs.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const p=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,ti.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{}))}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{PC(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,ti.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,UC);await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=JC(r.toolName),n=(0,s.join)(e,`${t}.json`),o=qt(r);await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=JC(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=JC(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,ti.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,ti.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,ti.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;PC(r,(0,c.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&&jC.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=JC(t.toolName),n=(0,s.join)(e.folderPath,UC,`${r}.json`);return new ps.E$({toolName:t.toolName,definitionPath:n,...xC(t.annotations)})}));return new ps.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 ps.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{IC(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&&jC.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){jC.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&jC.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){jC.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{PC(t,(0,c.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,LC),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=dE(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=JC(e.name);return new ps.E$({toolName:e.name,definitionPath:(0,s.join)(r,UC,`${t}.json`),...xC(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===HC))){const e=JC(HC);n.push(new ps.E$({toolName:HC,definitionPath:(0,s.join)(r,UC,`${e}.json`)}))}return new ps.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})})),l=a.reduce(((e,t)=>e+t.tools.length),0);return jC.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new ps.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{IC(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{jC.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,LC),i=new Set,a=new Map;for(const e of t){const t=dE(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,ti.readdir)(o),c=c.filter((e=>!e.endsWith(BC)&&!e.endsWith(WC)))}catch(e){if("ENOENT"!==rl(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++,RC.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),jC.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++,RC.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,UC);let h=0;try{h=(await(0,ti.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,RC.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),jC.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}))}TC.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),AC.gauge(e,i.size,this.getMetricTags({mcp_source:r})),$C.gauge(e,l.size,this.getMetricTags({mcp_source:r})),MC.gauge(e,d,this.getMetricTags({mcp_source:r})),DC.gauge(e,p,this.getMetricTags({mcp_source:r})),jC.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||jC.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())}}rE.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var nE=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},oE=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 sE(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 iE=(0,x.h)("local-exec:mcp");function aE(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function cE(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function lE(e){return new rr._Z({content:{case:"image",value:new rr.do({data:e.data,mimeType:e.mimeType})}})}function uE(e){return new rr._Z({content:{case:"text",value:new rr.zN({text:e})}})}function dE(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 hE(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client}});if(!n)return;const o=await fu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new rr.iz({result:{case:"error",value:new rr.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Ow.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 rr.iz({result:{case:"approved",value:new rr.Ke}}):null:new rr.iz({result:{case:"rejected",value:new rr.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new rr.iz({result:{case:"error",value:new rr.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class pE{constructor(e,t,r,n,o=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}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}}(Vt(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=nE(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),l=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),u=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),d=a.find((e=>e.name===t.name));if(void 0!==d&&(void 0!==u?d!==u:d.toolName!==t.toolName||d.clientKey!==i&&d.providerIdentifier!==i))return new rr.iz({result:{case:"error",value:new rr.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const h=void 0===u?void 0:await this.toolSet.getClient(o,u.clientKey).catch((()=>{})),p=await hE(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u,...void 0===h?{}:{client:h}});if(void 0!==p)return p;const f=await this.toolSet.getToolSet(o);let m;try{m=await f.execute(u?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(er(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new u_(t.providerIdentifier,l)),r instanceof u_){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new rr.iz({result:{case:"error",value:new rr.Nh({error:e})}}):new rr.iz({result:{case:"serverNotFound",value:new rr.JL({name:r.serverName,availableServers:r.availableServers})}})}if(er(r))return new rr.iz({result:{case:"toolNotFound",value:new rr.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const g=[];for(const e of m.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)g.push(uE(e.text));else if("resource"===r){const r=By(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await _C(n).then(lE,(e=>{iE.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));g.push(s??uE(Wy(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 _C(s)}catch(e){iE.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)}),g.push(uE(`[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}g.push(lE(i))}else if("image"!==r){const t=Wy(e);g.push(uE(t))}}const w=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 rr._Z({content:{case:"text",value:new rr.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:g,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.join(t,ml),n=s.join(r,`${(0,Xs.randomUUID)()}.txt`);await(0,ti.mkdir)(s.dirname(n),{recursive:!0});const o=gi(e,gl),i=wa(o),a=Buffer.byteLength(o,"utf8");return await(0,ti.writeFile)(n,o,"utf8"),new bl.pV({filePath:n,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===w)throw new Error("Failed to materialize MCP text output");const y=m.structuredContent&&"object"==typeof m.structuredContent&&!Array.isArray(m.structuredContent)?ar.Struct.fromJson(m.structuredContent):void 0,v=new rr.QW({content:w,isError:m.isError,structuredContent:y,resultMeta:void 0===m._meta?void 0:ar.Struct.fromJson(m._meta)});return new rr.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{oE(r)}var n}}class fE{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=nE(r,(0,c.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 rr.kP({result:{case:"error",value:new rr.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new rr.kP({result:{case:"success",value:new rr.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 rr.kP({result:{case:"success",value:new rr.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new rr.kP({result:{case:"error",value:new rr.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{oE(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 rr.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:sE(e.annotations)}))):[]}}class mE{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Ot),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=nE(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Ow.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ar.Value.fromJson(t.server),uri:ar.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ar.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new rr.ZD({result:{case:"rejected",value:new rr.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 rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new rr.ZD({result:{case:"error",value:new rr.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 rr.ZD({result:{case:"notFound",value:new rr.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,ti.realpath)(r),o=s.resolve(r,t.replace(/^\/+/,""));if(!aE(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.dirname(o);for(;;)try{if(!aE(n,await(0,ti.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==cE(e))throw e;const t=s.dirname(i);if(t===i)throw e;i=t}if(await(0,ti.mkdir)(s.dirname(o),{recursive:!0}),!aE(n,await(0,ti.realpath)(s.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,ti.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==cE(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,ti.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,ti.writeFile)(e,t)}return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:sE(r.annotations),metaJson:Ht(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:sE(r.annotations),metaJson:Ht(r._meta),content:{case:"blob",value:e}})}})}return new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return iE.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{oE(r)}}}async function gE(e,t){const r=dE(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,ti.readdir)(n)}catch(e){if("ENOENT"===rl(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,ti.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 wE=(0,x.h)("local-exec:mcp-disk-freshness-on-access"),yE="/mcps/",vE=(0,P.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),bE=(0,P.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),SE=(0,P.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),kE=(0,P.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),_E=new Map;function CE(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function EE({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 wE.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>dE(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void wE.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"};vE.increment(e,1,{...l,outcome:c}),bE.histogram(e,i.length,l),SE.histogram(e,a.length,l),kE.histogram(e,i.length+a.length,l),"mismatch"===c&&wE.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 xE(e,t,r,n=gE){if(void 0===r||(void 0===(o=r)||!CE(o).includes(yE)))return;var o;const s=function(e){const t=CE(e),r=t.indexOf(yE);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=_E.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{_E.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=dE(r.serverIdentifier);await EE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await EE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{wE.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);_E.set(i,d)}async function PE(e){try{return(await(0,ti.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function IE(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 RE(e,t,r=PE){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,ir.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof ir.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:IE(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}const TE=BigInt(0),AE=BigInt(8),$E=BigInt(16),ME=BigInt(65535);function DE(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function OE(e){const t=e.split(".");if(4!==t.length)return;let r=TE;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<>$E&ME)),t.push(Number(o.value&ME))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function NE(e){return OE(e)??function(e){const t=DE(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=FE(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<$E|BigInt(t)),TE)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=FE(n),i=FE(o);if(!s||!i)return;const a=s.length+i.length;return a>7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<<$E|BigInt(t)),TE)}}(e)}function jE(e,t){const r=DE(e),n=DE(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=NE(t.slice(0,r)),o=NE(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>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 LE(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=>jE(e,t)))}(r.hostname,t)}function UE(e){return e.trim().toLowerCase()}function BE(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function WE({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":UE(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(UE).filter((e=>e.length>0)),n=void 0===e?void 0:UE(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:BE(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}const HE=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function qE(e){return e.trim().split(/\s+/).filter(Boolean)}function zE(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 qE(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return HE.has(n)}function GE(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=GE(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(KE(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(KE(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(KE(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const ZE=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],XE=["cursor","molten glass"];function QE(e){return ZE.some((t=>e===t||e.startsWith(`${t}.`)))}const YE=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],ex=[{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"},...YE,{bundleId:ZE[0],name:"Cursor"}];function tx(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=ex.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}:QE(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>XE.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:ZE[0],name:"Cursor"}:void 0}const rx=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 nx(e){return rx.has(e.toLowerCase())}function ox(e){return`app/${e}`}function sx(e){return"object"==typeof e&&null!==e}function ix(e){return cx.includes(e)}function ax(e){if(!sx(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!sx(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!ix(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 cx=["pid","bundleId","path","appName"],lx=/^[+-]?\d+$/;var ux=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const dx="win32"===process.platform;function hx(e,t){return dx&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const px=(0,s.join)((0,o.homedir)(),".cursor","projects"),fx=(0,s.join)((0,o.homedir)(),".cursor","worktrees");function mx(e){return hx(px,e)&&e!==px}function gx(e){return hx(fx,e)&&e!==fx}function wx(e,t){const r=function(e){if(!hx(px,e))return;if(e===px)return;const t=(0,s.relative)(px,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function yx(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function vx(e){const t=rl(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:nl(e)}}}async function bx(e,t){const r=(0,ki.o1)(e,t);try{return yx(await(0,ti.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==rl(e))return yx(r,r,vx(e));try{if((await(0,ti.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,ti.readlink)(r)}catch{}return yx(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return yx(await(0,ti.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==rl(e))return yx(r,r,vx(e))}return yx(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===rl(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,ti.realpath)(t);return yx((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==rl(t))return yx(e,e,vx(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return yx(e,e,{status:"newFile"})}(r):yx(r,r,vx(e))}}}function Sx(e){return"resolved"===e.status||"newFile"===e.status}function kx(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 _x({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o}){return"workspace"===r.boundary&&!Cx(t,n)&&!Cx(t,o)&&!(xx(t,r.allowPaths)||e!==t&&xx(e,r.allowPaths))}function Cx(e,t){return t.some((t=>(0,ki.BJ)(e,t)))}function Ex(e){return e.flatMap((e=>{const t=(0,ki.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function xx(e,t){const r="win32"===process.platform?ki.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ki.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&ta(r(t),n)}))}const Px=/(?{const t=await bx(e);return Sx(t.resolution)?t.resolvedPath:(0,ki.o1)(e)})))}function Ux(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 Bx(e){return[...new Set(e)]}function Wx(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Hx({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 qx(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function zx(e){return"<"!==e.operator&&"<&"!==e.operator}function Gx(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Vx(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function Kx({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(Sx(a.resolution)){for(const e of r){const t=await o(e);if(Sx(t.resolution)&&Hx({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:s}))return"workspace-file"}return n&&oP(a.resolvedPath,i)?"tmp-file":void 0}}function Jx(e){return Bx(e.map((e=>e.trim())).filter(Boolean))}function Zx(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 Xx(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Qx(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Ir.r6({type:"word",value:e})));return new Ir.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Yx(e,t={}){return{type:e,...t}}function eP(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 tP(e,t){if("workspace"===e&&void 0!==t)return t}const rP={workspace:0,system:1};function nP(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 oP(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){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||!Hx({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 sP(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,oi.$b)(e.networkPolicy),n=(0,oi.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,oi._B)(e.networkPolicy),s=(0,oi._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!(rP[i]>rP[a])}class iP{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&sP(t,r);this.state=o?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!sP(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function aP(e){return e?.type??"undefined"}const cP=["skills","skills-cursor","rules","plugins"];async function lP(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function uP(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function dP({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 hP=/^\s*Read\s*\((.*)\)\s*$/,pP=/^\s*Write\s*\((.*)\)\s*$/;class fP{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.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy}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]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]):[[],[]],i=r.map((e=>this.compileReadDenyMatcher(e))),a=e=>i.some((t=>t(e)));return async(e,r)=>a(e)||a(r)||n&&_x({requestedAbsolutePath:e,realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s})}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:eP(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 Lx([...Ex(e),...(0,oi.r5)()])}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,Qs.r_)(e)))),...cP.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,oi.W1)(e)??[]));return Lx([...this.rootDirectories,...r,...n])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ki.o1)(e),o=await ll(n);if(null===o)return{type:"unsafeResolution",message:Ux("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(!mx(o)&&!gx(o)&&!t&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:o,requestedAbsolutePath:n});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const{perms:r,setting:n}=await this.readControlSetting();if("workspace"!==n.boundary||"unrestricted"===r.approvalMode)return!1;const o=await this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName);return!Cx(e,o)&&(!!_x({requestedAbsolutePath:t,realAbsolutePath:e,setting:n,resolvedWorkspaceRoots:o,resolvedAllowFolders:await this.resolvedReadAllowFolders(n.allowPaths)})&&{type:"needsApproval",approvalReason:n.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 shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Tx(n,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const a=await bx(t);if(!Sx(a.resolution))return{type:"unsafeResolution",message:kx(a.originalPath,a.resolution)};const l=a.resolvedPath,u=l;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",l))return{type:"permissionsConfig"};const d=a.originalPath.split(s.sep).pop()?.toLowerCase()??"",h=l.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=mx(u),f=gx(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",l))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(l))return!1;const g=await this.getPermissions();if("workspace_readonly"===g.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===g.approvalMode)return!1;for(const e of this.rootDirectories){const t=await bx(e);if(!Sx(t.resolution))continue;const r=t.resolvedPath;if((0,ki.BJ)(l,r)){const e=(0,s.relative)(r,l).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const w=async()=>{let e,t,n="";try{n=await ac(l),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,ux.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 y,v=!1;for(const e of this.rootDirectories){const t=await bx(e);if(!Sx(t.resolution))continue;const r=t.resolvedPath;if((0,ki.BJ)(l,r)){v=!0,y=r;break}}const b=v?void 0:function(e){if(!gx(e))return;const t=(0,s.relative)(fx,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(fx,t[0]):void 0}(l);if(!v&&void 0===b){if(function(e){return oP(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(l))return!1;if(wx(l,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(l.startsWith(e)){const e=l.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=l;let _=(0,s.relative)(S,k).split(s.sep);if(_=_.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&_.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${_[_.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,oi.OK)(l,S)){const e=_[_.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const C=await this.checkCursorFileProtection(_);if(C)return C;if(!0===g.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await w();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{Ax(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 ll(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Ux("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}}:{kind:"allow"}}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($x.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:aP(l),requestedPolicyType:aP(n),effectiveRequestedPolicyType:aP(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:qr(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 $x.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:aP(l),requestedPolicyType:aP(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.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,v="allowlist"===a&&i.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==v,S=v?v.map(Qx):d,k=void 0!==v?v.map(Zx):S.map((e=>[e.fullText.trim()].filter(Boolean))),_=void 0!==y?y.commands.map(Zx):k;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,oi.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,oi._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 C;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,oi.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,oi.wG)(tP(e.readBoundary,e.additionalReadPaths),tP(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),m&&$x.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});const E=[],x=[];let P=[],I=[],R=[];const T=Jx(i.smartAllowlistDenylist??[]);if(T.length>0){I=[];const t=_.map((e=>e[0]??""));for(let e=0;e<_.length;e++){const r=_[e];if(r&&0!==r.length&&T.some((e=>Xx(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&($x.info(e,"Command blocklist: commands require approval",{count:I.length}),E.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));$x.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const n=k.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(zE(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),Jx(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=JE(P,R),t=e.length>0?e.join(", "):P.join(", ");x.push(`Not in allowlist: ${t}`)}C=o&&0===I.length,C&&$x.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,$=S.map(((e,t)=>new iP(e,n,A,k[t])));if((0===S.length||f&&!b)&&!c){$x.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:aP(n),userConfiguredPolicyType:aP(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const o={type:Ow.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:w}};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{allRedirectsAreWorkspaceFileSafe: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 j=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:I});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return $x.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=qr(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&&Px.test(r)||Rx(r,Px,Ix)||Rx(r,/(?0&&(j.hasSecurityDenies||j.hasSoftDenies||!j.allCommandsRunnable);if(void 0!==g&&G.push(g),L&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),E.length>0&&(V||G.push(...E),z=!1),!V)if(b&&x.length>0)G.push(...x);else if(j.unapprovedCommands.length>0){const e=JE(this.generateAllowlistPatterns(j.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):j.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(j.hasSecurityDenies&&(V||(j.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),j.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${j.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=j.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");$x.info(e,"Shell permissions: commands not in team allowlist",{commandCount:j.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J=G.join(" • "),Z=[];if(z){const e=void 0!==g?$.filter((e=>"allowlisted"!==e.state)):j.unapprovedCommands;Z.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const X=b&&x.length>0,Q=X?P:Z,Y=X&&R.length>0?R:void 0,ee="insecure_none"!==n.type&&"insecure_none"!==l.type,te="insecure_none"!==n.type,re=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,E.length>0?"command_blocklist":void 0,b&&x.length>0?"smart_allowlist_miss":void 0,j.unapprovedCommands.length>0?"unapproved_commands":void 0,j.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));$x.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:aP(n),userConfiguredPolicyType:aP(l),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:z,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:re,commandCount:$.length,unapprovedCommandCount:j.unapprovedCommands.length,deniedCommandCount:j.deniedCommands.length,notInTeamAllowlistCount:j.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSecurityDenies:j.hasSecurityDenies,hasSoftDenies:j.hasSoftDenies});const ne={type:Ow.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&ee,isSandboxEnabled:"allowlist"===a&&te,canAllowlist:z,notAllowedCommands:Q,suggestedAllowlistEntries:Y,smartModeApprovalReason:g,smartModeApprovalRequestId:w}};r.onApprovalRequested?.();const oe=await this.pendingDecisionStore.requestApproval(ne);if(oe.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.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,d=l?c.commands.map(Qx):u;if(0===d.length)return!1;const h=l?c.commands.map(Zx):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Zx):h,f={type:"insecure_none"},m=d.map(((e,t)=>new iP(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=Jx(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>Xx(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const w=await this.teamSettingsService.getAutoRunControls();if(void 0!==w&&m.some((e=>this.isInTeamBlocklist(w,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:w,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const{userSandboxDataFolderName:t,teamAdminPolicy:r}=await this.getPermissions(),n=void 0!==t&&t.length>0?(0,s.join)((0,o.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,i=await this.foldPerUserFilePolicy(e,n),a=i.skipStatsigDefaults?i:await this.applyStatsigDefaults(i),c=await this.loadPerRepoFilePolicy(a.type);if("unavailable"===r){const{policy:e}=await(0,oi.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,oi.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const l=void 0===r?await this.buildTeamAdminPolicy(a.type):Yx(a.type,function(e){return"workspace"===e.readBoundary?e:void 0===e.networkPolicy?{}:{networkPolicy:e.networkPolicy}}(r)),u=(0,oi._B)(e.networkPolicy),{policy:d}=await(0,oi.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c,teamAdmin:l});return u?{...d,networkPolicy:(0,oi.T6)()}:d}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,oi.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,oi.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,oi.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};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,oi.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,oi._B)(e.networkPolicy))return e;const r={default:"deny",allow:Bx(t.allowlist)};return{...e,networkPolicy:(0,oi.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,oi.tv)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Yx(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await 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:Bx(i.allowlist)}:{},...i.denylist.length>0?{deny:Bx(i.denylist)}:{}}:void 0:(0,oi.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});return void 0===t?void 0:Yx(e,t)}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){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return 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=bx,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=Wx();for(const e of l){if(Vx(e))continue;const o=u?Wx():d,{operator:i,targetText:l}=e,p=e.destinationFds;if(">&"===i){const e=Gx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===i){const e=Gx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!qx(i)||void 0===l){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await Kx({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(zx))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c,redirectsAllowlistSafe:l}}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?{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=this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Ow.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",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}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ia({matchForms:t.parsingResult?ra({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?($x.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.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==nP(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=nP(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){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return 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 n of e)zE(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?hP:pP}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=ea(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,ki.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,ki.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 ta(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{Tx(o,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:l}=t,u=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:EC(r.annotationsJson)}(t,r?.annotations),d=e=>{this.mcpAllowlistLog?.(e)};if(d(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return d(`[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 h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return d(`[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=dP({server:uP(a),tool:i});let b,S,k;switch(w.kind){case"block":return d(`[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 d(`[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 d(`[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?(d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(d(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:u}):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,...jx(r,u),providerIdentifier:a,args:l,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:u});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return d(`[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 d(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;d(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return d(`[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,...jx(r,u),providerIdentifier:a,args:l,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Ax(o)}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(uP(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=ax(e.meta?.["cursor/computerUseScope"])??ax(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])=>ix(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&&lx.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?tx(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&&lx.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:tx(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 QE(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":YE.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.":ex.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=nx(o.app.bundleId)?void 0:dP({server:r.serverId,tool:ox(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=uP(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(uP(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||nx(e)?void 0:dP({server:this.computerUse.serverId,tool:ox(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??EC(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=uP(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}){Mx.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&&jE(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&&function(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=UE(e);return 0!==r.length&&t.some((e=>UE(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}(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 mP=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 gP=65536,wP=1048576,yP=(0,x.h)("LocalReadExecutor"),vP=async(e,t,r,n)=>{const o=setTimeout((()=>{yP.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function bP(e){return BigInt(Math.min(e,4294967295))}async function SP(e,t){if(0===t)return(0,ti.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,ti.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function CP(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 EP=Buffer.from("\n---\n");function xP(e,t){const r=e.length;if(r<2*EP.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(EP,r-EP.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+EP.length,r-4).toString("utf-8"))?o:r}const PP=[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 IP(e){return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:e,reason:"File content is binary data, not text"})}})}function RP(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=TP(s,e),c=TP(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function TP(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 AP(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function $P(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 MP(e,t,r){const n=$P((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 DP(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=AP(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=gi(c,o)),{text:c,truncated:l}}function OP(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=AP(e.slice(t,o));const i=s.length>n||on&&(s=gi(s,n)),s.lengthn?{text:e.text+gi(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function NP(e,t){if(e.truncated)return e;const r=FP(e,t);return{text:r.text,truncated:r.truncated}}function jP(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=FP(n,"\n")),n=FP(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function LP(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 UP(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?tr:Math.min(tr,e.maxChars+2)}function BP(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 WP extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function HP(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return qP(r)>t?t:0}return 0}function qP(e){return e>=240?4:e>=224?3:e>=192?2:1}class zP{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 WP}validate(e){let t=e;if(this.carry.length>0){const r=qP(this.carry[0]??0)-this.carry.length;if(e.length0?Math.min(t,wP):wP,o=await SP(e,r);return o.length===t&&(0,n.isUtf8)(o)||Ta(new fa.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===wP&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function KP(e){const t=await(0,ti.stat)(e),r=await dc(e);if(r.isBinaryFile)return;const n=GP({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await VP(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function JP(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,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,j=0,L=!1,U=!1;const B=e=>{let t=e;return!L&&t.length>0&&(L=!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>=tr,q=()=>v||w&&g>=tr,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=tr-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:gi(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=tr-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:gi(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++:j++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.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===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t1&&A>tr;)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-HP(e));return Q=new zP(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 fa.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,ni.createReadStream)(t,{highWaterMark:gP,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 WP;throw e}return}const i=(0,ni.createReadStream)(t,{highWaterMark:gP,signal:e.signal,...s}).pipe(ma.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=NP(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&&Sc(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)+gP,ae=e=>e.text.length>ie?{text:gi(e.text,ie),truncated:!0}:e,ce=()=>jP({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(jP({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class ZP{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}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,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new nr.sV({result:{case:"error",value:new nr.F_({path:o,error:_i})}});const i=(0,ki.o1)(o,this.workspacePath),a=await vP(e,"permissionsService.shouldBlockFileRead",3e3,(()=>lP(this.permissionsService,i)));if(a){const r=await vP(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await fu(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:Ow.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 nr.sV({result:{case:"rejected",value:new nr.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new nr.sV({result:{case:"permissionDenied",value:new nr.lW({path:i})}})}void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,i);try{const r=await vP(e,"stat",3e3,(()=>(0,ti.stat)(i)));if(r.isDirectory())return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=or(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=or(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 vP(e,"getFormatForFile",3e3,(()=>dc(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=sc(i);if(l){const t=await vP(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await _C(e)}catch(t){const r=await CC(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await CC(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,ti.readFile)(i))));return"undecodable"===t.kind?new nr.sV({result:{case:"invalidFile",value:new nr.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 nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(u){const t=await vP(e,"readPdfBinary",3e3,(()=>(0,ti.readFile)(i)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await vP(e,"readBinaryFile",3e3,(()=>(0,ti.readFile)(i)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(c.isBinaryFile)return IP(i);{const n=this.useStreamingRead,o=!n||await vP(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>tr){const n=await vP(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=GP(t,r.encodingHint);try{return await JP(e,t,r,o,n)}catch(o){if(o instanceof WP)return await JP(e,t,r,await VP(t.file,t.stats.size),n);throw o}}(e,{file:i,stats:r,format:c},t,o)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"content",value:BP(n.content,n.truncated,t)},totalLines:n.totalLines,fileSize:bP(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await vP(e,"readText",3e3,(()=>ac(i,t.encodingHint))),a=await vP(e,"countLines",3e3,(()=>wa(s))),l=function(e,t,r){const n=RP(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:MP(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=UP(t);return u.length>h&&(u=BP(u.substring(0,h),!0,t),d=!0),u.lengthSP(t,r.size)));if(o&&(i=s,PP.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return IP(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=kP(e),o=xP(e,n);if("utf-8"!==CP(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=$P((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=OP(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=kP(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=xP(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=$P((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=DP(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,UP(n));return new nr.sV({result:{case:"success",value:new nr.mE({path:t,output:{case:"content",value:BP(a.content,a.truncated,n)},totalLines:a.totalLines,fileSize:bP(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function XP(e){return Buffer.from(e,"utf16le").toString("utf16le")}var QP=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},YP=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 eI(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 tI(e){return`Path '${e}' is neither a file nor a directory`}async function rI(e){const t=await(0,ti.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function nI(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ki.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 oI extends Error{}function sI(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function iI(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 aI(e){switch(e){case"content":return new ay.vD({result:{case:"content",value:new ay.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new ay.vD({result:{case:"files",value:new ay.T7({ripgrepTruncated:!0})}});case"count":return new ay.vD({result:{case:"count",value:new ay.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function cI(e,t){let r=Buffer.concat(e);t&&(r=r.subarray(0,r.lastIndexOf(10)+1));const n=r.toString("utf8");return n.includes("�")?{stdout:n,stdoutBytes:r}:{stdout:n}}function lI(e){return/^(utf-?16|ucs-?2)/i.test(e)}const uI=(0,x.h)("local-exec/grep"),dI=(0,P.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"]}),hI=(0,P.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"]});function pI(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function fI(e){try{return(0,ni.existsSync)(e)}catch{return"check_failed"}}function mI(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function gI(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 wI(e,t,r,n){return{...vI(e),...n,cwd:t,cwdExists:fI(t),errorMessage:nl(r),errorCode:rl(r),errno:mI(r),syscall:gI(r,"syscall"),errorPath:gI(r,"path")}}function yI(e){return new Error(`Path does not exist: ${e}`)}function vI(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,ni.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,ni.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,ni.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,ni.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,ni.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,ni.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,ni.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 e=r.concat("node_modules.asar");try{t.asarExists=(0,ni.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,ni.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,ni.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class bI{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;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}computeRelativeTarget(e,t){const r=(0,ki.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,ki.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,ki.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ki.o1)(t.path,this.singleWorkspacePath??e);return(0,ki.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 Oc(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,ti.stat)(e)).isFile())return;const{encoding:t}=await dc(e);return lI(t)?t.toLowerCase():void 0}catch{return}}((0,ki.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,ki.o1)(s.file,t),i=await ll(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 RE(t,(e=>(0,ki.o1)(n(e),r)));return s.statTimedOut&&(uI.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),hI.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,bI.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const h=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),p=await this.buildArgs(t,r,"files_with_matches",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,i);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?bI.HARD_MAX_OUTPUT_LINES:bI.CLIENT_LIMIT_LINES,d=bI.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 cy;let s=0,i=0,a=0;for(;ly(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(l,u,d)),g=m.totalFiles>bI.CLIENT_LIMIT_LINES;let w=m.files;n&&(w=await this.keepNewestPage(h.ctx,w,t,(e=>e),i),g&&(w=w.join("\0").split("\0")));const y=(await this.filterBlockedFiles(w.map((e=>({file:e}))),t)).map((({file:e})=>e)),v=w.length-y.length,b=new ay.T7({files:y,totalFiles:py(m.totalFiles-v),clientTruncated:g,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new ay.vD({result:{case:"files",value:b}}),timedOut:f.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(a)}var l,u,d}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const h=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),p=await this.buildArgs(t,r,"count",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,i);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?bI.HARD_MAX_OUTPUT_LINES:bI.CLIENT_LIMIT_LINES,d=bI.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 cy;let i=0;for(;ly(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}}(l,u,d)),g=n?await this.keepNewestPage(h.ctx,m.counts,t,(e=>e.file),i):m.counts,w=await this.filterBlockedFiles(g,t),y=w.reduce(((e,t)=>e+t.count),0),v=g.length-w.length,b=g.reduce(((e,t)=>e+t.count),0)-y,S=new ay.xA({counts:w.map((e=>new ay.sS({file:e.file,count:py(e.count)}))),totalFiles:py(m.totalFiles-v),totalMatches:py(m.totalMatches-b),clientTruncated:m.totalFiles>bI.CLIENT_LIMIT_LINES,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new ay.vD({result:{case:"count",value:S}}),timedOut:f.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(a)}var l,u,d}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const l=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),u=await this.buildArgs(t,r,"content",n),d=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,h=bI.CLIENT_LIMIT_LINES*(d?2:1),p=await this.executeRg(l.ctx,t,u,h,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=await this.decodeLinesAsRead(l.ctx,p,t,i),{byFile:m,totalLines:g,totalMatchedLines:w,clientTruncated:y,ripgrepTruncated:v}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return QP(o,(0,c.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 cy;let a=0,c=0,l=0,u=0;for(;ly(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:py(l),totalMatchedLines:py(a),totalFiles:py(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{YP(o)}}(f,bI.CLIENT_LIMIT_LINES,h,l.ctx),b=Array.from(m.values()),S=await this.filterBlockedFiles(b,t),k=b.filter((e=>!S.includes(e))),_=k.reduce(((e,t)=>e+t.matches.length),0),C=k.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),E=n?await this.orderNewestFirst(l.ctx,S,t,(e=>e.file),i):S,x=new ay.Zp({matches:E.map((e=>new ay.uI({file:e.file,matches:e.matches.map((e=>new ay.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:py(g-_),totalMatchedLines:py(w-C),clientTruncated:y,ripgrepTruncated:v||p.timedOut||p.stdoutByteCapped});return{result:new ay.vD({result:{case:"content",value:x}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(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=QP(s,(0,c.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),l=function(e,t){const r=[],o=new cy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&ly(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)))],d=new Map,h=performance.now()+bI.LINE_ENCODING_TIMEOUT_MS;let p=0;for(;p{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(bI.ripgrepTimeoutError());let f;try{const e=s;f=(0,oi.spawnInSandbox)((0,oi.Ko)(),r,{cwd:t},e),0}catch(r){if(p(),pI(r)){const n=(0,oi.Ko)();if(uI.error(e,"rg_diagnostics.spawn_throw",void 0,wI(n,t,r,i)),!1===fI(t))return u(yI(t))}return u(r)}const m=[],g=[];let w=0,y=0,v=0,b=!1,S=!1;const k=()=>{if(!d)try{p();const e=cI(m,!0);""===e.stdout?u(bI.ripgrepTimeoutError()):c({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:S}),f.kill()}catch{}};o.addEventListener("abort",k,{once:!0});const _=()=>{o.removeEventListener("abort",k),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",_,{once:!0}),f.stdout?.on("data",(e=>{if(!S&&!b)if(w+=e.length,w>l){S=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,b=!0;try{f.kill()}catch{}break}v+=r;const o=t>=0?e.subarray(0,t):e;m.push(o)}else m.push(e)})),f.stderr?.on("data",(e=>{y+=e.length,y<=l&&g.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_),p(),pI(r)){const n=(0,oi.Ko)();if(uI.error(e,"rg_diagnostics.spawn_enoent",void 0,wI(n,t,r,i)),!1===fI(t))return void u(yI(t))}u(r)})),f.on("close",(t=>{d=!0,o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_);const r=cI(m,S),n=Buffer.concat(g).toString("utf8");p(),c({...r,stderr:n,exitCode:t??0,timedOut:!1,stdoutByteCapped:S})}))}))}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 ll(t[0]);return null===r?{error:eI(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await rI(t[0])?{error:tI(e)}:{resolvedTarget:r}}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const i=QP(n,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),a=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(o=l)&&"files_with_matches"!==o&&"count"!==o)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:a},h=Ki(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(a);if((0,ki.fl)({targetPath:t.path,workspacePaths:a,mainWorktreePath:p?.mainWorktreePath}))return new ay.Ud({result:{case:"error",value:new ay.ts({error:ki.PS})}});const f=this.findOutsideTargets(t.path,a);let m=t,g=a;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new ay.Ud({result:{case:"error",value:new ay.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,r.resolvedTarget),g=a.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,a)){if(!(0,ki.BJ)(s,o))continue;const i=await ll(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await rI(s))return new ay.Ud({result:{case:"error",value:new ay.ts({error:tI(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:eI(m.path);return new ay.Ud({result:{case:"error",value:new ay.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(i.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(i.ctx,d),t=e?sI(bI.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=aI(u),n++,o=!0;continue}if(!1===fI(s))return new ay.Ud({result:{case:"error",value:new ay.ts({error:`Path does not exist: ${s}`})}});const a=t??sI(bI.MAIN_TIMEOUT_MS);try{const t=await this.runMode(i.ctx,u,s,m,e,a.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof oI))throw t;if(r[s]=aI(u),n++,o=!0,!e)break}finally{a!==t&&a.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(iI));if(this.reportDeadlineReached(i.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw bI.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=>nI(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 ay.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 ay.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 ay.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),c=new ay._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ki.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new ay.Ud({result:{case:"success",value:c}})}catch(e){if(m.path){const e=(0,ki.o1)(m.path,this.singleWorkspacePath);try{await(0,ti.stat)(e)}catch(t){return new ay.Ud({result:{case:"error",value:new ay.ts({error:`Path does not exist: ${e}`})}})}}return new ay.Ud({result:{case:"error",value:new ay.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{YP(n)}var o}}bI.MAIN_TIMEOUT_MS=25e3,bI.INDEXED_GREP_TIMEOUT_MS=25e3,bI.INDEXED_GREP_CONTEXT_TIMEOUT_MS=bI.INDEXED_GREP_TIMEOUT_MS+100,bI.HARD_MAX_OUTPUT_LINES=1e4,bI.CLIENT_LIMIT_LINES=2e3,bI.LINE_ENCODING_TIMEOUT_MS=2e3,Ln.object({record_v:Ln.number().int().nullish(),pid:Ln.number().int().nonnegative().nullish(),version:Ln.string().nullish(),started_at:Ln.number().nullish(),control_sock:Ln.string().nullish(),runtime_dir:Ln.string().nullish(),data_dir:Ln.string().nullish(),config_path:Ln.string().nullish(),log_path:Ln.string().nullish(),metrics_addr:Ln.string().nullish(),exe:Ln.string().nullish()}),Ln.object({mountpoint:Ln.string().nullish(),capabilities:Ln.array(Ln.string()).nullish(),nfs_transport:Ln.string().nullish(),bind_ignored:Ln.object({active:Ln.array(Ln.string()).nullish()}).passthrough().nullish()}),Ln.object({daemon_alive:Ln.boolean().nullish(),mounts:Ln.array(Ln.unknown()).nullish(),data_plane:Ln.object({enabled:Ln.boolean().nullish()}).passthrough().nullish()});const SI=Ln.number().int().nonnegative(),kI=Ln.object({line_no:Ln.number().int().positive(),kind:Ln.enum(["match","before","after"]),text:Ln.string().optional(),bytes:Ln.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Ln.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Ln.object({type:Ln.literal("file"),path:Ln.string(),lines:Ln.array(kI)}),Ln.object({type:Ln.literal("summary"),files_searched:SI,more:Ln.boolean(),stop_reason:Ln.string().nullable(),skipped:Ln.object({over_size:SI,size_unknown:SI,budget_exhausted:SI,fetch_failed:SI,unreadable:SI})}),Ln.object({type:Ln.string()}),(0,x.h)("local-exec/grove-grep");var _I=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),CI=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},EI=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 xI{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{CI(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ki.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,ti.stat)(n)}catch(e){return"ENOENT"===rl(e)?function(e){const t=or(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:"No active terminals."})}}):new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:`Path does not exist: ${n}`})}}):new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:nl(e)})}})}if(!r.isDirectory())return new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Ki(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 _I.fv({result:{case:"timeout",value:new _I.ze({directoryTreeRoot:a})}}):new _I.fv({result:{case:"success",value:new _I.PC({directoryTreeRoot:a})}})}catch(e){return new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{EI(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return CI(o,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{EI(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{CI(i,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),l=new _I.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(a,l);const d={charactersUsed:a.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=jc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,s.resolve)(t,e),n=await ll(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{EI(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 _I.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]=py(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=py(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 _I.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)}}var 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 II=1e4,RI=5e3,TI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class AI{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,tII&&(this.fullOutput="")}getOutput(){return this.totalChars<=II?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=II))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class $I{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Ei-this.kept.length;this.full=e.length>=t,this.kept+=gi(e,t)}get text(){return this.kept}}function MI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class DI{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 Ir.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new Ir.QR(o)};return new Ir.W4({result:i,sandboxPolicy:Ji(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,oi.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new AI,a=new $I,l=new $I;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,oi.ue)((0,oi.Xw)({...process.env,...TI,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,_l.D9)(kl.spawn,y.executable,y.args,w):(0,oi.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:fy(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=Ir.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=Ir.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:MI(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,c.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ki.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new Ir.W4({result:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Ir.W4({result:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:s,reason:mu(l.reason)})}});a=l.policy,Fi()&&(a=Wi(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:u,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{PI(r)}}}var OI=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function FI(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class NI{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:FI(t.cursor),advance:!1!==t.advance});return new OI.Ev({result:{case:"success",value:new OI.iS({events:e.events.map((e=>new OI.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 OI.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new OI.Ev({result:{case:"error",value:new OI.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class jI{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new xr.nt({result:{case:"error",value:new xr.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new xr.nt({result:{case:"success",value:new xr.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class LI{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,R.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 UI(e,t){return`${e}:${(0,Xs.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function BI(e,t){const r=new ri.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=UI(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 WI=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),HI=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class qI{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"),zI(GI(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),zI(new WI.GL({result:{case:"success",value:new WI.uX({path:t.path,diagnostics:e.map(VI)})}}),await o))}catch(e){return r("unavailable"),zI(GI(t.path,e instanceof Error?e.message:String(e)),await o)}}}function zI(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function GI(e,t){return new WI.GL({result:{case:"error",value:new WI.HW({path:e,error:t})}})}function VI(e){return new HI.oQ({severity:KI(e.severity),range:new bl.Q6({start:new bl.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new bl.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function KI(e){switch(e){case 1:return HI.h_.ERROR;case 2:return HI.h_.WARNING;case 3:return HI.h_.INFORMATION;case 4:return HI.h_.HINT;default:return HI.h_.UNSPECIFIED}}class JI{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 HI.Ek({result:{case:"success",value:new HI.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new HI.Ek({result:{case:"error",value:new HI.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new HI.Ek({result:{case:"error",value:new HI.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{ZI(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 HI.oQ({severity:this.convertSeverity(e.severity),range:e.range?new bl.Q6({start:new bl.yX({line:e.range.start.line,column:e.range.start.character}),end:new bl.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 HI.h_.ERROR;case 2:return HI.h_.WARNING;case 3:return HI.h_.INFORMATION;case 4:return HI.h_.HINT;default:return HI.h_.UNSPECIFIED}}}async function QI(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 ty().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 YI(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 YI(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 YI{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 eR=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]=nR(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=sR(e)}],[/^\+\+\+\s/,e=>{u(),n.to=sR(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},tR=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,rR=/^(a|b|i|w|c|o|1|2)\//,nR=e=>{const t=e?.match(tR);return t?.map((e=>e.replace(rR,"").replace(/("|')$/,"")))},oR=/^\\?['"]|\\?['"]$/g,sR=e=>{let t=iR(e,"-+").trim();return t=cR(t),t.replace(oR,"").replace(rR,"")},iR=(e,t)=>{if(e=uR(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=lR(t);return e.replace(new RegExp(`^${r}+`),"")},aR=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,cR=e=>{const t=aR.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},lR=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${uR(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,uR=e=>`${e??""}`,dR=(0,x.h)("local-mercurial-diff"),hR=5242880,pR="0000000000000000000000000000000000000000";let fR,mR;async function gR(e,t,r={}){const n=await async function(){if(void 0===fR&&(fR=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 ti.stat(t)).isFile())continue;return"win32"!==process.platform&&await ti.access(t,ni.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===fR){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return fR}();return await new Promise(((o,s)=>{const i=(0,kl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new Ic.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"}`))}}))}))}async function wR(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await ti.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!==mR)return mR;const e=await ti.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await gR(e,["help","environment"]);mR=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){mR=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await ti.rm(e,{recursive:!0,force:!0})}return mR}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await gR(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await ti.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function yR(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function vR(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 bR(e){const t=s.resolve(e);try{return await ti.realpath(t)}catch{return t}}function SR(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 kR(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function _R({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await gR(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>hR?"":gR(e,["cat","-r",t,"--",r])}async function CR(e,t,r){const n=function(e){switch(e){case jn.ek.NAME_STATUS:return jn.ek.NAME_STATUS;case jn.ek.NAME_STATUS_AND_NUMSTAT:return jn.ek.NAME_STATUS_AND_NUMSTAT;case jn.ek.FILE_DIFFS:return jn.ek.FILE_DIFFS;case jn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return jn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return jn.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await gR(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){kR(t),r.push("log");const n=(await gR(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===pR)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await gR(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==pR)return n;const o=(await gR(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==pR)return o;const s=(await gR(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:pR}({cwd:t,baseRef:r.baseRef,commands:o});else if(kR(r.baseRef),o.push("log"),a=(await gR(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(kR(r.ref),o.push("log"),c=(await gR(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 gR(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new jn.o$({diffs:eR(t).map((e=>function(e){const t=new jn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new jn.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:jn.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 gR(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 ti.stat(r);if(n.size>hR){const t=await async function(e){const t=(0,Xs.createHash)("sha256"),r=await ti.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 ti.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 jn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=SR(e.contents);if(0===t.length)return new jn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new jn.QP({from:"/dev/null",to:e.path,chunks:[new jn.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!==jn.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===jn.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 _R({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 ti.stat(e);t.afterFileContents=r.size>hR?"":await ti.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await _R({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=SR(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,Xs.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 gR(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:pR,g=(await gR(t,["status","-0"])).length>0}dR.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new jn.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 dR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return dR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const ER=(0,x.h)("local-git-diff");function xR({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function PR(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 xR(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function IR(e){const t=eR(e);return new jn.o$({diffs:t.map((e=>function(e){const t=new jn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new jn.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:jn.Wf.UNSPECIFIED})}function RR(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:wa(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 TR=["main","master","develop"];async function AR(e,t){const r=s.join(e,t),n=await ti.lstat(r);if(n.isSymbolicLink())return{contents:await ti.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await ti.readFile(r,"utf8"),path:t,isSymlink:!1}}async function $R(e,t,r){const n=ty(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await PR(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 bR(t);let n=await bR(e);if(yR(n,r))return;let o=!1;for(;vR(n,r)&&!yR(n,r);){try{if((await ti.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?wR(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await wR(e)?"none":"mercurial"}(t,o);if(ER.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw ER.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return CR(e,t,r);const a=function(e){switch(e){case jn.ek.NAME_STATUS:return jn.ek.NAME_STATUS;case jn.ek.NAME_STATUS_AND_NUMSTAT:return jn.ek.NAME_STATUS_AND_NUMSTAT;case jn.ek.FILE_DIFFS:return jn.ek.FILE_DIFFS;case jn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return jn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return jn.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await PR(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of TR){const r=`origin/${t}`;try{return await PR(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await PR(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await PR(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 PR(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=IR(h);else{const t=xR(d);if(r.computePatchId||!await async function(e){return(await PR(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 PR(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),ER.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 PR(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 AR(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${RR([e])}\n\\ No newline at end of file`:await PR(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...IR(t).diffs)}}if(a!==jn.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===jn.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 PR(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 PR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await AR(t,s.to)).contents}catch{try{s.afterFileContents=await PR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){ER.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 QI({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 PR(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){ER.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,RR(f))):void 0,v=!0===r.returnHeadSha?(await PR(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await PR(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new jn.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 MR{async execute(e,t){return $R(e,t.cwd,t)}}var DR=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class OR{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 DR.M({allowlisted:r})}}var FR=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),NR=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 jR(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function LR(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function UR(e){return e instanceof Error?e.message:String(e)}function BR(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: ${UR(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const WR=(0,fa.promisify)(kl.execFile);class HR{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(!jR(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,ir.wj)(Promise.all(e),HR.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 ti.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 ti.mkdir(this.stagingDir,{recursive:!0}),await ti.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:FR.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:FR.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:FR.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 ti.rename(e,t)}catch(e){if(!LR(e,"EXDEV"))throw e}try{await ti.copyFile(e,t)}catch(e){throw await ti.rm(t,{force:!0}).catch((()=>{})),e}try{await ti.unlink(e)}catch(e){throw await ti.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 ti.open(e,"wx");return await t.close(),e}catch(e){if(!LR(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,_l.D9)(WR,"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,_l.D9)(WR,"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:HR.PROXY_TARGET_FPS,includeBrandTag:!0}),await ti.access(n,ti.constants.R_OK)}catch(t){const r=(0,c.fU)(e);throw r?.setAttribute("error.type",function(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}(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,_l.D9)(WR,"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 ${HR.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${HR.PROXY_TARGET_FPS}fps`)}return HR.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await ti.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await jg(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${HR.DEFAULT_REFRESH_RATE}Hz`),o=HR.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${HR.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${HR.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",HR.PROXY_PRESET,"-crf",String(HR.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,_l.D9)(kl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.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);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.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);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.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:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,_l.D9)(kl.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 ti.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(jR(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{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),LR(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();try{const o=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!jR(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${UR(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await ti.access(d,ti.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=LR(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${UR(e)}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:BR(t,r,a,n)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=UR(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:BR(o,r,a,n)})}})}const m={profileVersion:HR.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:HR.PROXY_TARGET_FPS,codec:"h264",profile:HR.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:o,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await ti.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await ti.rm(g,{force:!0}).catch((()=>{})),e}try{await ti.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${UR(e)}`)}return this.clearActiveRecordingIfCurrent(r),new FR.Tj({result:{case:"saveSuccess",value:new FR.ol({path:g,recordingDurationMs:ar.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new FR.Tj({result:{case:"failure",value:new FR.yH({error:UR(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,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`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===FR.$u.UNSPECIFIED)return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case FR.$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 ti.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await ti.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await jg(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,o);r=a;const l=function(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}(this.display);n=new Vg({displayNum:l,resolution:i}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new FR.Tj({result:{case:"startSuccess",value:new FR.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await ti.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new FR.Tj({result:{case:"failure",value:new FR.yH({error:e instanceof Error?e.message:String(e)})}})}}case FR.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new FR.Tj({result:{case:"failure",value:new FR.yH({error:"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 FR.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!jR(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await ti.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new FR.Tj({result:{case:"discardSuccess",value:new FR.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await ti.rm(r,{force:!0,recursive:!0}),n=!0}catch{}this.activeRecording=null;const o=t instanceof Error?t.message:String(t),s=n?"":`. Session may remain at: ${r}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{NR(r)}}}async function qR(e){const t=await(0,ti.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 qR(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 zR(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(...zR(t,e,s))}))}return n}async function GR(e){if(!await(0,ti.access)(e,ti.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await qR(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>zR(e,"",r===t.length-1))).join("\n")}async function VR(e,t){return GR(s.join(e,"agent-notes",t))}async function KR(e){return GR(s.join(e,"agent-notes","shared"))}HR.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,HR.PROXY_TARGET_WIDTH=1920,HR.PROXY_TARGET_FPS=60,HR.PROXY_CRF=17,HR.PROXY_PRESET="veryfast",HR.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",HR.DEFAULT_REFRESH_RATE=60;var JR=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},ZR=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 XR=(0,x.h)("local-exec:request-context"),QR=Symbol("sectionLoadTimedOut");async function YR(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{JR(o,(0,c.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{ZR(o)}}async function eT(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 tT(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,oi.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,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Lr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ar.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 rT={type:"object",properties:{},additionalProperties:!1};function nT(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Wt.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new ps.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?ar.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oT(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 ps.E$({toolName:e.toolName,...xC(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?ar.Value.fromJson(e.inputSchema):void 0}}})));return!Bt(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===HC))||o.push(new ps.E$({toolName:HC,...r?{}:{description:qC,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rT)}:{inputSchema:ar.Value.fromJson(rT)}}})),new ps.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 ps.U_({enabled:!0,mcpDescriptors:n})}function sT(e){const t=e?.trim();return t||void 0}function iT(e,t){const r=function(e){return sT(e.serverIdentifier)}(e);if(r)return r;const n=sT(e.serverName);return n?t.get(n)??n:void 0}class aT{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(XR.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(XR.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=>iT(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=>iT(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=>(XR.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:Vt(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cT(e){return new rr._W({result:{case:"success",value:new rr.pv({servers:e.servers.map((e=>new rr.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new ps.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0,metaJson:Ht(e._meta),...xC(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lT{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==rr.ew.FORCE_IF_MISSING&&t.refreshPolicy!==rr.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 cT({...r,servers:n})}return cT(r)}}class uT{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.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:I,isAttributionDisabledByAdmin:R,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=I,this.isAttributionDisabledByAdmin=R,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.onRequestContext=c.onRequestContext,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),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)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,be.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=JR(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Jc(n.ctx,this.gitExecutor,t),s=o?await Zc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?Xc(s):void 0};this.cachedWorkspaces.set(t,i)}catch(e){r.error=e,r.hasError=!0}finally{ZR(r)}}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,be.q6)(),r=JR(e,(0,c.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)&&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{ZR(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=JR(t,(0,c.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,l,u,d]=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([]))]),h=Math.round(performance.now()-o);return h>1e3&&XR.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{ZR(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=JR(r,(0,c.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;const a=(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 Lr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Vc(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:c,branchName:l}=await async function(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(YR(e,t,r,n)),o(eT(e,t,r,n))]);return{status:s,branchName:i}}(n.ctx,t.gitExecutor,r.repoPath,3e3);return void 0===c&&(i=!1),new Lr.DS({path:r.repoPath,status:c,branchName:l,remoteUrl:r.remoteUrl,isOriginBacked:Vc(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:a,gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{ZR(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=JR(n,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=JR(e,(0,c.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath){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{ZR(e)}},a=performance.now(),l={},u=(e,t)=>{const r=performance.now();return t.finally((()=>{l[e]=Math.round(performance.now()-r)}))},d=e=>function(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(QR)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}(e,this.sectionLoadTimeoutMs),h=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),[p,f,m,{gitRepos:g,gitRepoInfoComplete:w,gitStatusInfoComplete:y},v,b,S,k,_,C]=await Promise.all([u("globalCache",d(i())),u("mcpState",d(h((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(o.ctx))))),u("env",tT(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})),u("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),u("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?VR(s,t.notesSessionId):Promise.resolve(void 0)),u("sharedNotes",this.agentNotesEnabled&&s?KR(s):Promise.resolve(void 0)),u("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),u("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),u("agentSkills",d(h((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([]))))),u("adminCommandDenylist",d(h((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))]),E=p===QR,x=f===QR,P=_===QR,I=C===QR,R=E?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:p,T=x?{servers:[]}:f,A=P?[]:_,$=I?void 0:C;(E||x||P||I)&&XR.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:E,mcpState:x,agentSkills:P,adminCommandDenylist:I});const M=performance.now()-a;for(const[e,t]of Object.entries(l))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(M)),M>1e3&&XR.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(M),...l});const D=this.mcpMetaToolEnabled?oT(T,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,O=this.attributionConfigProvider?.get(),F=!k&&(O?.attribution?.attributeCommitsToAgent??!0),N=!k&&(O?.attribution?.attributePRsToAgent??!0),j=new Lr.bb({rules:R.rules,env:m,gitRepos:g,gitRepoInfoComplete:w,repositoryInfo:R.codebaseReference?[{relativeWorkspacePath:R.codebaseReference.relativeWorkspacePath,repoName:R.codebaseReference.repoName,repoOwner:R.codebaseReference.repoOwner,isTracked:R.codebaseReference.isTracked,isLocal:R.codebaseReference.isLocal,orthogonalTransformSeed:R.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:R.codebaseReference.pathEncryptionKey}]:[],...nT(T,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:v,sharedNotesListing:b,customSubagents:R.customSubagents,mcpFileSystemOptions:S,mcpMetaToolOptions:D,supportsMcpAuth:!0,commitAttributionMessage:F?"enabled":void 0,prAttributionMessage:N?"enabled":void 0,agentSkills:A,adminCommandDenylist:$?.rules??[]});return null!==R.cloudRule&&void 0!==R.cloudRule&&(j.cloudRule=R.cloudRule),this.reportSectionCompleteness&&(j.rulesInfoComplete=!E,j.customSubagentsInfoComplete=!E,j.agentSkillsInfoComplete=!P,j.mcpInfoComplete=!x,j.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==S,j.envInfoComplete=!0,j.gitStatusInfoComplete=y),j}catch(e){n.error=e,n.hasError=!0}finally{ZR(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=JR(r,(0,c.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 Lr._G({result:{case:"success",value:new Lr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(nl(e)),new Lr._G({result:{case:"error",value:new Lr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{ZR(r)}}}function dT(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Ir._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hT=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 pT{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Ir.W4({result:{case:"success",value:new Ir.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Ji(e.sandboxPolicy)}):new Ir.W4({result:{case:"failure",value:new Ir.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Ji(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?{perRepo: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?Ir.Lv.TIMEOUT:Ir.Lv.USER_ABORT:Ir.Lv.UNSPECIFIED:void 0,u=fy(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 Ir.W4({result:{case:"timeout",value:new Ir.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:Ji(o)}):e.signal.aborted?new Ir.W4({result:{case:"rejected",value:new Ir.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Ji(o)}):new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:Ji(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,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dT(t),l=(0,ki.o1)(i);if(!t.parsingResult)return new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(zr(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId},s);if("block"===e.kind)return new Ir.W4({result:gu(o,l,e.reason)});u=s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Hr(t)},s);if("block"===e.kind)return new Ir.W4({result:gu(o,l,e.reason)});u=e.policy}if(Fi()&&(u=Wi(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await ul(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,i,a,u)}catch(e){r.error=e,r.hasError=!0}finally{hT(r)}}}var fT=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mT{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Ir.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fT.e({allowlisted:n})}}class gT{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Ir.jK({status:Ir.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wT=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 yT=(0,x.h)("local-exec:shell-stream");class vT{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===Ir.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:Ir.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:Ir.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 bT(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class ST{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}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,be.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new Ir.jK({status:Ir.iA.ACCEPTED,shellResult:o}):new Ir.jK({status:Ir.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(Ar).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:bT()},""!==e.toolCallId&&e.timeoutBehavior===Ir._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,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dT(t),l=(0,ki.o1)(i),u=Date.now(),d=new Ir.HO(di(o).structured),h=ca({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new Ir.FI({event:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:mu(p.reason)})}}));if(yT.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}),zr(t))yT.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"});else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:l,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Hr(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bT()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yT.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 Ir.FI({event:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=mu(n.reason);return void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:r})}}))}s=n.policy,yT.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}if(Fi()&&(s=Wi(o,d)),s&&"insecure_none"!==s.type){const e=await ul(this.ignoreService);s={...s,ignoreMapping:e}}yield new Ir.FI({event:{case:"start",value:new Ir.tD({sandboxPolicy:Ji(s)})}});const f=t.timeoutBehavior===Ir._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?{perRepo: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 vT(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new Ir.W4({result:{case:"success",value:new Ir.QR({shellId:E,pid:C,command:o,workingDirectory:l,msToWait:fy(Date.now()-u),backgroundReason:Ir.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&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 D=k?.iterate()??b;try{for await(const r of D)if("stdout"===r.type)x+=r.data,yield new Ir.FI({event:{case:"stdout",value:new Ir.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new Ir.FI({event:{case:"stderr",value:new Ir.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;I=!0,r.aborted&&(n=e.signal?.aborted?Ir.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?Ir.Lv.TIMEOUT:Ir.Lv.USER_ABORT),yield new Ir.FI({event:{case:"exit",value:new Ir.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:fy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof oi.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yT.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new Ir.FI({event:{case:"sandboxUnsupported",value:new Ir.rI({command:o,workingDirectory:l,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||I||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===Ir.Jg.USER_REQUEST?Ir.Jg.USER_REQUEST:Ir.Jg.TIMEOUT,s=n===Ir.Jg.USER_REQUEST?Date.now()-u:a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:l,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new Ir.FI({event:{case:"backgrounded",value:new Ir.Y9({shellId:r,command:o,workingDirectory:l,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new Ir.FI({event:{case:"exit",value:new Ir.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:Ir.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wT(n)}}}const kT={kind:"absent"};class _T{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 ri.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(RT(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=RT(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=RT(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=RT(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=RT(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=RT(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}async function CT(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IT(t);const r=await xT(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}class ET{constructor(e,t,r,n){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n}async execute(e,t,r){const n=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ki.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===n)return this.inner.execute(e,t,r);const o=this.reads.begin(n);try{let s,i;try{s=await lP(this.permissionsService,n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}if(!1!==s&&"needsApproval"!==s.type)return await this.readAndForget(e,t,r,n,o);if(!1!==s){const s=await this.inner.execute(e,t,r),i=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await xT(t)}catch{return}}(s,n.resolvedPath);return this.commit(n,o,s,i),s}try{i=await xT(n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}const a=await this.inner.execute(e,t,r);return this.commit(n,o,a,i),a}finally{this.reads.end(n,o)}}commit(e,t,r,n){"fileNotFound"!==r.result.case?void 0===n||"success"!==r.result.case||"content"!==r.result.value.output.case?this.reads.forget(e,t):this.reads.record(e,{kind:"fingerprint",...n},t):this.reads.record(e,kT,t)}async readAndForget(e,t,r,n,o){const s=await this.inner.execute(e,t,r);return this.reads.forget(n,o),s}}async function xT(e){try{const t=await(0,ti.stat)(e);if(!t.isFile()||t.size>tr)return}catch(e){return TT(e)}let t;try{t=await(0,ti.open)(e,function(){const e=ni.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>tr)return;const n=(0,Xs.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=tr;){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>tr)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return TT(e)}finally{await(t?.close())}}function PT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}async function IT(e){try{return await(0,ti.stat)(e),!0}catch(e){if(AT(e))return!1;throw e}}function RT({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function TT(e){if(!AT(e))throw e}function AT(e){const t=rl(e);return"ENOENT"===t||"ENOTDIR"===t}var $T=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class MT{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new $T.M({allowlisted:r})}}var DT=r("node:constants");class OT extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}const FT=new fa.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),NT=new Map([["€",128],["‚",130],["ƒ",131],["„",132],["…",133],["†",134],["‡",135],["ˆ",136],["‰",137],["Š",138],["‹",139],["Œ",140],["Ž",142],["‘",145],["’",146],["“",147],["”",148],["•",149],["–",150],["—",151],["˜",152],["™",153],["š",154],["›",155],["œ",156],["ž",158],["Ÿ",159]]),jT=new Set([194,195,226,239]),LT=/\p{Lu}/u,UT=new Set([" ","­","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),BT=new Set(["¿","¡"]),WT=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,BT],[209,BT],[211,BT],[218,BT],[220,BT]]),HT=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),qT=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function zT(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:NT.get(e)}function GT(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&<.test(e[t-1]))return}else{if(UT.has(s))return;if(!0===WT.get(r)?.has(s))return;if(3===n&&HT.has(s)&&UT.has(e[t+2]))return}let i;try{i=FT.decode(o)}catch{return}return qT.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function VT(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=GT(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const KT=["mojibake","replacement_chars"];function JT(e){return e<=1?"1":e<6?"2-5":"6+"}function ZT(e){return e<=0?"0":JT(e)}function XT(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=nA(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function QT(e,t){return e<=t?"existing_only":"new_damage"}function YT(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(VT(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return VT(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 eA(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function tA(e,t,r){const n=VT(r,1e3);if(0===n.length)return eA("mojibake");const o=void 0===e?[]:VT(e,Math.max(n.length,6));return{detector:"mojibake",outcome:QT(n.length,o.length),file:XT(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:YT(n,o)}}function rA(e,t,r){const n=Aa(r);if(0===n)return eA("replacement_chars");const o=void 0===e?0:Aa(e);return{detector:"replacement_chars",outcome:QT(n,o),file:XT(e,o,t),afterCount:n,beforeCount:o}}function nA(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 oA=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 sA(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":oA.get(t)??"other"}const iA=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function aA(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:iA.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function cA(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:sA(t.path),encoding:nA(t.encoding),code_page:aA(t.pages),run_count:JT(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":ZT(n)),before_count:ZT(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}var lA=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 uA=(0,x.h)("LocalWriteExecutor"),dA=(0,P.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"]}),hA=async(e,t,r,n)=>{const o=setTimeout((()=>{uA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function pA(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function fA(e){try{return(await(0,ti.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===rl(e))return"missing";throw e}}async function mA(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await fA(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,ti.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 pA(e)}class gA{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,onWriteForAiTracking:i,writeFileMutationGuard:a,toolCallReads:c}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.onWriteForAiTracking=i,this.writeFileMutationGuard=a,this.toolCallReads=c}async execute(e,t){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Hp.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const r=(0,ki.o1)(t.path,this.workspacePath),n=this.toolCallReads,o=void 0!==n&&""!==t.toolCallId?n.take({toolCallId:t.toolCallId,resolvedPath:r}):void 0,s={writeStarted:!1},i=()=>{void 0===o||s.writeStarted||n?.restore(o)};try{const n=await this.executeWithRecord(e,t,r,o?.recorded,s);return vA(n)&&i(),n}catch(e){throw i(),e}}async executeWithRecord(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const a=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}(i,(0,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=wx(r,["assets","agent-tools","swarm-agents"]);if((0,ki.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:ki.PS})}});let h,p,f=!1;try{if((await(0,ti.stat)(r)).size<=xi){const e=await hA(a,"readText before write",3e3,(()=>cc(r,t.encodingHint)));h=e.text,p=e.encoding}else f=!0}catch{}const m=(await bx(r)).resolvedPath,g=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await hA(a,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(a,m,l)));if(g){const e=await hA(a,"handleBlockReason",3e3,(()=>fu(g,{onNeedsApproval:async(e,o)=>{const s="fileEdit"!==o?.type||o.isNewFile,i="fileEdit"===o?.type?o.diffString:l,a="fileEdit"===o?.type?o.blockReason:void 0;if(await CT(n,m))return wA(r);const c=await this.pendingDecisionProvider.requestApproval({type:Ow.Write,details:{path:r,reason:e,isNewFile:s,diffString:i,before:h,after:l,blockReason:a},toolCallId:t.toolCallId});return c.approved?null:new Rr.v3({result:{case:"rejected",value:new Rr.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new Rr.v3({result:{case:"rejected",value:new Rr.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const w=await hA(a,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,ti.stat)(e)).isFile())return;const n=await(0,ti.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!==w)return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:w})}});const y=(0,s.dirname)(m);if(await async function(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IT(t)}catch{return!1}}(n,y))return wA(r);try{await hA(a,"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=await mA(e,t),i=0;for(;ir)throw pA(e);try{await(0,ti.mkdir)(a,{recursive:!1})}catch(r){const n=rl(r);if("EEXIST"===n){if("directory"!==await fA(a))throw r;i+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(a);if(n===a||"missing"!==await fA(n))throw r;o=await mA(e,t),i=0;continue}throw r}i+=1}}(y)))}catch(e){const t=rl(e);return"EACCES"===t||"EPERM"===t?new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:y,operation:"create_directory",error:"Permission denied"})}}):new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:nl(e)})}})}let v,b,S;if(void 0!==u)v=u,b=0;else{const e=await hA(a,"getBufferForWrite",3e3,(()=>uc(r,l,this.workspacePath,t.encodingHint)));v=e.buffer,b=e.lines,S=e.format.encoding}const k=()=>hA(a,"writeFile",3e3,(async()=>{if(await CT(n,m))throw new Error(PT(r));let e;a.signal.throwIfAborted(),o.writeStarted=!0,await async function(e,t,r){let n;try{n=await(0,ti.open)(e,function(){const e=ni.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=rl(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof ni.constants.O_NOFOLLOW}(t))throw new OT(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,ni.realpathSync)(e)}catch{throw new OT(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new OT(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new OT(e,`Refusing to write to non-regular file at ${e}`);await n.truncate(0);const s=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i{try{await k()}catch(e){throw _=e,C=!0,e}};try{void 0===this.writeFileMutationGuard?await k():await this.writeFileMutationGuard.runExclusive(m,E)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!C||e!==_))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof OT)return new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=rl(e);return"EACCES"===t||"EPERM"===t?new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===rl(e)?new Rr.v3({result:{case:"noSpace",value:new Rr.bM({path:r})}}):"EDQUOT"===t?new Rr.v3({result:{case:"error",value:new Rr.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 Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:nl(e)})}})}if(this.fileChangeTracker&&void 0===u&&!d&&!f){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(r,h,l,e)}if(this.onWriteForAiTracking&&void 0===u&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:h,afterContent:l,metadata:e})}catch(e){uA.warn(a,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const x=v.byteLength;let P;if(void 0!==u||f||d||this.recordEncodingChecks(a,r,h,p,l),t.returnFileContentAfterWrite)try{P=await hA(a,"readText after write",3e3,(()=>ac(r,t.encodingHint)))}catch{}return new Rr.v3({result:{case:"success",value:new Rr.j6({path:r,linesCreated:b,fileSize:x,...void 0!==P&&{fileContentAfterWrite:P}})}})}catch(e){i.error=e,i.hasError=!0}finally{lA(i)}}recordEncodingChecks(e,t,r,n,o){try{const s={path:t,encoding:n,pages:Dl.pages()};for(const t of function(e,t,r){return[tA(e,t,r),rA(e,t,r)]}(r,n,o))dA.increment(e,1,cA(t,s))}catch(t){for(const t of KT)dA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});uA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}}}function wA(e){return new Rr.v3({result:{case:"error",value:new Rr.QM({path:e,error:PT(e)})}})}class yA extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function vA(e){return"error"===e.result.case&&e.result.value.error===PT(e.result.value.path)}const bA=(0,x.h)("local-exec:provider"),SA=new Set,kA=new wl.AsyncLocalStorage;class _A extends ne{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of SA)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of SA)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,ni.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,oi.$6)(n);return(0,oi.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.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,oi.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});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 du(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,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new pu(c,this.askpassConfig)),this.shellManager&&(c=new hu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pT(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(Tr,BI(l)),this.register(Er,BI(new DI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _T,d=e.overrideWriteExecutor??new gA(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u});this.register($r,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(vA(e))throw new yA(e);return e}))},BI(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof yA)return e.result;throw e}}}}(d));const h=e.overrideDeleteExecutor??new Nw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking);this.register(ye,BI(h)),this.register(Se,BI(new Ww)),this.register(ke,new MR);const p=this.mcpStateAccessor??new aT(this.mcpLease),f=e.overrideGrepExecutor??new bI(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:p,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep});this.register(_e,BI(f));const m=e.overrideReadExecutor??new ET(new ZP(this.permissionsService,a,{mcpStateAccessor:p,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),u,this.permissionsService,a),g=new ur(m);this.register(dr,g),e.registerRedactedReadExecutor&&this.register(hr,g);const w=e.overrideLsExecutor??new xI(this.permissionsService,this.ignoreService,a);this.register(Ft,BI(w)),this.register(ve,BI(new XI(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(ge,BI(new qI(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Kt,BI(new Cr(new pE(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(dr))))),this.register(Jt,BI(new fE(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Zt,BI(new mE(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(Xt,BI(new lT(p,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const y=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(p,t,e),v=BI({execute:(e,t,r)=>{const n=kA.getStore();return void 0!==n&&(n.ran=!0),y.execute(e,t,r)}});this.register(jr,{execute:async(t,r,n)=>{const o={ran:!1},s=await kA.run(o,(()=>v.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 p.getState(t),l=nT(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oT(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=[],bA.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new $u(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(de,BI(this.backgroundShellExecutor)),this.shellStreamExecutor=new ST(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(Ar,function(e,t){const r=new ri.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=UI(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new LI(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor)),void 0!==e.agentStoreConflictDrainer&&this.register(le,new NI(e.agentStoreConflictDrainer)),this.register(Ur,new mT(this.permissionsService)),this.register(Qt,new OR(this.permissionsService)),this.register(En,new MT(this.permissionsService));const b=new gT(this.shellStreamExecutor);this.register(Br,BI(b));const S=!1===e.enableWriteBackgroundShellStdin?new jI((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new jI(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(he,BI(S)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(we,BI(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new HR({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Nr,BI(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uT(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,ki.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,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,onRequestContext:r.onRequestContext});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,SA.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}getRecordScreenExecutor(){return this.recordScreenExecutor}withPendingShells(e){return new oe(e,[te(Ar,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.rebuildRequestContextOnRulesChange&&(SA.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 CA(e){return e.replace(/\\/g,"/")}function EA(e,t){for(const r of t){const t=CA(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var xA;function PA(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return xA.Plugin;const n=CA(e.fullPath);return EA(n,r.builtinDirs)?xA.Builtin:Wm(e.fullPath,t).inAgentStore?xA.UserStore:EA(n,r.userDirs)?xA.UserHome:(EA(n,r.workspaceDirs),xA.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"}(xA||(xA={}));var IA=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 RA=(0,fa.debuglog)("merged-agent-skills"),TA=(0,x.h)("merged-agent-skills");class AA{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,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(RA("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 TA.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()]),l=i.flat(),u=this.getPromptSortContext?.(),d=qm(l,u??Um);let h=d;return a.ok?a.paths.length>0&&(h=d.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)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes($A));var t})),void 0!==u?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[km(e.userHomeDirectory).dirPath],r=Rm(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 Im(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:PA(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(h,u):h}catch(e){t.error=e,t.hasError=!0}finally{IA(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()}),AA.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()}}AA.CHANGE_COALESCE_MS=1500;const $A=`/${wm.configDir}/${wm.subdir}/`,MA=(0,x.h)("skill-sync-manifest"),DA=".sync-manifest.json";async function OA(e,t){try{const r=await(0,ti.readFile)((0,s.join)(e,DA),"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:(MA.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===rl(r)||MA.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function FA(e,t,r){e.skills[t]={lastSyncedAt:r}}function NA(e,t){delete e.skills[t]}var jA=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 LA=(0,x.h)("builtin-skills-sync");function UA(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function BA(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 WA(e){const t=Gp(e.content),r=UA(t.data)?t.data:{};return Vp(`${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={...UA(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 HA(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 qA(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,ti.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,ti.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,ti.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,ti.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,ti.writeFile)(t,r,"utf-8")}try{await(0,ti.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==rl(e))throw e}try{await(0,ti.rename)(n,r)}catch(e){throw i&&(await(0,ti.rename)(o,r),i=!1),e}i&&(await(0,ti.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,ti.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,ti.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===rl(t)||LA.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,ti.mkdir)(n,{recursive:!0}),await(0,ti.writeFile)(o,i,"utf-8"),!0}async function qA(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,ti.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===rl(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await qA(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function zA(e,t){try{return(await(0,ti.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===rl(r)||LA.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function GA(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,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),l=t.skillDir??km((0,o.homedir)()).dirPath;await(0,ti.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([OA(l,i),zA(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([VA((0,s.join)(r,"SKILL.md")),"canvas"===e?VA((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}})));LA.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){LA.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):LA.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:(t.canvasKit,Cm((0,o.homedir)()).dirPath),m=void 0!==f&&await VA((0,s.join)(f,_m)),g=new Set([...p.keys(),...d,...m?[_m]:[]]),w=e=>void 0!==f&&e===_m?f:l,y=e=>void 0!==f&&e===_m?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&&Wd(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)BA(t),f!==l&&await(0,ti.mkdir)(f,{recursive:!0}),await HA(i,f,{id:e,fileContent:WA(t),resources:t.resources??{}})?v++:b++,FA(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,ti.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),NA(u,e),h&&(S.push(e),LA.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||FA(u,e,a)}catch(t){LA.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),n=(0,s.join)(e,DA);await(0,ti.mkdir)(e,{recursive:!0}),await(0,ti.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,ti.rename)(r,n)}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===rl(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?LA.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):LA.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{jA(r)}var n}async function VA(e){try{return await(0,ti.stat)(e),!0}catch(e){const t=rl(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const KA=(0,x.h)("managed-skills-sync");function JA(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 ZA{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(...oh(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=JA(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var XA=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 QA(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class YA{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??Mu,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: ${nl(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: ${nl(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(Kf));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Kf(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=QA(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 Gf({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${nl(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,ti.realpath)(r);if(!(await(0,ti.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,ti.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 Wf(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}: ${nl(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,be.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,c.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=QA(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,l=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??i.length>0;if(!a&&!u&&!l)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 d=(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??Mu,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(zf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>Gf({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Mu,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,ti.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,ti.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,ti.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{ip(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,ti.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 Wf(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,ti.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=Vf(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=>Vf(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:l,loadCursorFirstParty:u&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:d}))):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: ${nl(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{XA(e)}}}var e$=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function t$(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function r$({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||LE(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class n${constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new e$.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new e$.aYW({}))}}function o$(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 s${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 i${constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new s$((()=>this.fetchSettings())),this.hostMcpBridgeClients=new WeakSet,this.teamRepos=new s$((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new s$((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){const e=this.settingsGeneration;try{const t=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e>=this.lastFetchedGeneration&&(this.lastFetchedSettings=t,this.lastFetchedGeneration=e),t}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){return this.settings.get().catch((()=>{}))}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(n){if(function(e,t){return!yy(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,my.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=r$({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?r$({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}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,my._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=t$(t.url);return void 0!==n&&r.some((e=>t$(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}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=WE({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===e$.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===e$.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===e$._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===e$.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:o$(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 a$=new sy,c$={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Jc((0,be.q6)(),a$,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?ei(r):void 0),workspaceRoots:n,createdAt:new Date}}},l$=(0,x.h)("ControlledConversationActionManager");class u${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,R.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 Gr.QFf({action:{case:"cancelAction",value:new Gr.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 R.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 R.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 R.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 R.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,R.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Gr.QFf({action:{case:"userMessageAction",value:new Gr.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){l$.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof R.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 R.W2("ControlledConversationActionManager disposed")))}}var d$=r("../cursor-sdk-local-runtime/dist/utils/logger.js");const h$="x-blob-encryption-key";function p$(e,t){const r={...t};return void 0!==r[h$]||(0,$n.TU)(e)&&(r[h$]=e),r}const f$=new Map;function m$(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function g$(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 w$(e){return new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:e})})}})}function y$(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function v$(e){e?.catch((e=>{d$.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const b$=new Set(["mcp.slack.com","setup.shopify.com"]);async function S$(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!==(i=e,a=r.restMcpHost,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?zv(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!b$.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await xb(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===Cb(t.CLIENT_ID)?{...c,...t,CLIENT_ID:c.CLIENT_ID}:{...c,...t}:c:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}class k${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 S$(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class _${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 C${constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class E${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 ky(t,n.configPath??"another config")}return await o(e,r)}}class x${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={};for(let e=0;e({prefix:t,scope:r,fileSource:new T_(e,"enterprise"===r||"env"===r?cv:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new _$(t,l),p=new C$(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,lv.indexOf(t)0?[new E$(f)]:[]],g=new A_(u?new k$(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new x$(y)}static init(e,t,r,n=!1,o,i={}){const a=new U_(s.join(r,"mcp-auth.json"));(async function(e){await(0,ti.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new Ey(s.join(r,"mcp-approvals.json"),t);return new P$(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 I$="cursor-plugins/local";function R$(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===I$)return r}class T$ extends p_{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class A${constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,ti.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,ti.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,ti.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class $${constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return d$.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&N$(r))continue;const e=F_(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}}):d$.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 M${constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:F$(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function D$(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};return{async createLease(a){const c=a.workspaceState,l=c.projectRoot??c.workingDirectory,u=c.projectDirectory;if(!l||!u)return new h_;const d=new A$((0,s.join)(u,"mcp-disabled.json")),h=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return P$.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new U_((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new Ey((0,s.join)(n,"mcp-approvals.json"),r),p=[new Iy,new Cy(h),new D_(t),new _y(a)],f=[];return c&&f.push({prefix:"",loader:new O_((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new O_((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),O$(f)}({teamSettingsService:t,projectRoot:l,projectDirectory:u,ignoreApprovals:r,disabledStore:d,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),p=[],f=e.inlineMcpServers??{};if(Object.keys(f).length>0){const e=new U_((0,s.join)(u,"mcp-auth.json")),r=[new Iy,new D_(t)];p.push({prefix:"",loader:new A_(new M$(f),e,r,i)})}const m=R$(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new Ey((0,s.join)(u,"mcp-approvals.json"),l),o=new U_((0,s.join)(u,"mcp-auth.json")),a=[new Iy];r||a.push(new Cy(e)),a.push(new D_(t),new _y(d));const c=new ZA(m.pluginsService),h=new A_(new $$(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new h_;const g=O$(p),w=await g.load(e.initializationCtx??(0,be.q6)(),e.cache);return new T$(w)}}}function O$(e){return 1===e.length?e[0].loader:new x$(e)}function F$(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 N$(e){return"claude-plugin"===e.pluginSource}function j$(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function L$(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class U${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>U$.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===$r.symbol||e===ye.symbol?{kind:"path"}:e===Tr.symbol||e===Ar.symbol||e===de.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=L$(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===Ar.symbol&&j$(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new Ir.FI({event:{case:"hookContext",value:new Ir.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===$r.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=L$(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,ir.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 B$(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}U$.CARRIERS_BY_EXEC_ID_MAX=32,Error,kl.execFileSync,new Map,ni.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 W$=["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(B$);function H$(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(q$,"\n\n"):r).trim()}(e,W$)}["system_reminder","system-reminder"].map(B$);const q$=/\n{3,}/g;function z$(e){const t=(0,Qs.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,Qs.sh)(e.parentConversationId);return`${Qs.O2}/${r}/subagents/${t}.${e.ext}`}return`${Qs.O2}/${t}/${t}.${e.ext}`}function G$(e){const t=(0,Qs.sh)(e.conversationId);return`${Qs.O2}/${t}.${e.ext}`}function V$(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(z$({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(z$({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(G$({conversationId:e.conversationId,ext:n}));return n}var K$;(()=>{const e=globalThis.Intl?.Segmenter;e&&new e(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(K$||(K$={}));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},Z$=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 X$(e){switch(e){case Gr.xyI.AGENT:return"agent";case Gr.xyI.ASK:return"ask";case Gr.xyI.PLAN:return"plan";case Gr.xyI.DEBUG:return"debug";case Gr.xyI.TRIAGE:return"triage";case Gr.xyI.MULTITASK:return"multitask";case Gr.xyI.CUSTOM:return"custom";case Gr.xyI.UNSPECIFIED:default:return"agent"}}function Q$(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 Y$(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 eM=new TextEncoder,tM=new TextDecoder,rM=new class{serialize(e){const t=JSON.stringify(e,Q$);return eM.encode(t)}deserialize(e){const t=tM.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Y$):JSON.parse(t)}};function nM(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function oM(e){return"system"!==e.role&&!nM(e)}function sM(e,t){return"user"===e.role&&"user"===t.role}async function iM(e,t,r){const n=await t.getBlob(e,r);return n?Gr.Anz.fromBinary(n).summarizedMessages:[]}async function aM(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=rM.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 cM(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 aM(e,t,o,n);r&&n.messages.push(r)}return n}async function lM(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=aM(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 dM(e){return H$(e)}const hM=/[\s\S]*?<\/think>/gi,pM=/[\s\S]*?<\/thinking>/gi,fM=/\n{3,}/g;function mM(e){let t=e;return t.includes("<")&&(t=t.replace(hM,"").replace(pM,"")),(t.includes("\n\n\n")?t.replace(fM,"\n\n"):t).trim()}function gM(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?dM(e):e;return r?mM(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=mM(t?dM(e.text):e.text);return uM({...e,text:r},!1)}return uM(e,t)})).filter(Boolean).join("\n")}function wM(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?dM(n):n,s="assistant"===e.role?mM(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?dM(r.text):r.text,s="assistant"===e.role?mM(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 yM(e){return e.endsWith("\n")?e:`${e}\n`}function vM(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 bM(e){if("system"===e.role||nM(e))return;const t=wM(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 SM{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=z$({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=J$(o,(0,c.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=vM(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:l,writeText:u,writeJson:d}=this.options;if(i&&a&&l&&!u&&!d&&!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 h=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=J$(n,(0,c.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,c.OA)(o.ctx),a=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await iM(i,t,e);return s+=r.length,await cM(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of g)a.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=J$(n,(0,c.VI)(e.withName("hydratePromptMessages")),!1),y=await cM(i,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const v=y.messages.filter(oM);return a.push(...v),a}catch(e){n.error=e,n.hasError=!0}finally{Z$(n)}}(s.ctx,this.blobStore,t);if(0===h.length&&0===o.jsonlLines.length)return!0;let p;if((this.options.writeText||e)&&(p=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=gM(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(h)),this.options.writeText){const e=p??"",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=wM(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(h);if(e||o.jsonlLines.length>0){const n={mode:X$(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&&sM(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=bM(e);t&&r.push(t)}return r.join("\n")}(h);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&p?.trim())try{const t=(await e(p)).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"),yM(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{Z$(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const l=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},u=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await l())};let d,h=0;const p=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 iM(e,t,s)}catch{continue}await lM(e,t,r,o,{skipFailedReads:!0,visit:n})}return await lM(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{oM(e)&&await n(e)}}),o}((0,c.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(h++,1!==h?(2===h&&d&&(sM(d,e)||await u(bM(d)),d=void 0),await u(bM(e))):d=e)}));d&&await u(bM(d));for(const e of t.terminalLines)await u(e);await l(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",p.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",p.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",p.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",p.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",p.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",p.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",p.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=vM(o),l=a.jsonlLines.length>0;if(i===n&&!l&&!o.overviewFactory)return i;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||l))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const d=J$(s,(0,c.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&l)try{return await u(this.resolveFilePath(r,"jsonl"),yM(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 cM(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=bM(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=yM(s.join("\n"));await u(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{Z$(s)}}}function kM(e){return Object.values(Ce).some((t=>t===e))}function _M(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 CM(e){return Je(e)?`prompt:${e.prompt}`:`command:${e.command}`}function EM(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class xM{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(CM(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=CM(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(!Me(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Me(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Ee&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Me(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=Le(r,this.logger),o=_t(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=_t(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,...EM(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))kM(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))kM(e)&&t.add(e);return t}}const PM="Read",IM="Write",RM="Delete",TM="List",AM="Grep",$M="Shell",MM="ReadLints";function DM(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const OM=new Set([PM,IM,RM,TM,AM,MM]);function FM(e){const t=DM(e,"tool_name"),r=[DM(e,"file_path"),"string"==typeof t&&OM.has(t)?DM(DM(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const NM=(0,x.h)("cli-hooks-executor");function jM(e){try{return(0,ni.statSync)(e).isFile()}catch{return!1}}const LM="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function UM(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function BM(e,t){const r=UM(e,t);if("string"==typeof r||null===r)return r}class WM{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,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,ih.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,Qs.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=V$(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,ti.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,Qs.Rv)((0,o.homedir)(),this.workspacePath),n=V$({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,ti.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,...EM(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?qe(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?qe(n,t):n).some((e=>Ze(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=UM(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 et.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Ce.subagentStop){const e=BM(t,"subagent_id"),r=BM(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:[this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Ce.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return He(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=He(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 He(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return He(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=qe(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)Je(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):Ze(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,ki.o1)(t,r),[o,i,a]=await Promise.all([(0,ki.DN)(n),(0,ki.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ki.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:FM(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===Ce.stop||e===Ce.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 qe(n,u))Ze(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=Ue(`Hook execution failed: ${n}`),r=it(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return NM.warn((0,be.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;if(1===t.length)return t[0];const r=Ye.includes(e),n=e===Ce.sessionStart,o=e===Ce.workspaceOpen,s=Ke.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=tt(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?rt(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=tt(i[e],l)}var a,c;return i}(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=it(e,Ue(`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=it(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=it(e,Ue(`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=it(e,Ue(`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=at(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=at(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=ot({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+LM}),{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+LM}),{success:!1,source:s,index:i})}const y=Qe(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=ot({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,be.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 nt(e)?st(0,{permission:"allow"}):e===Ce.beforeSubmitPrompt||e===Ce.sessionStart?st(0,{continue:!0}):e===Ce.stop?st(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=it(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=it(e,Ue(`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=vt.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:jM}):t.command;let w;if(m)w=e?bt(g):g;else if("windows_temp_file"===f){d=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,ti.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 | ${bt(t)} }`+yt(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+yt(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=BM(n,"conversation_id")??void 0,v=BM(n,"session_id")??void 0,b=BM(n,"transcript_path"),S=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),k=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:S?.at(-1)??y:v,_=this.buildHookEnvironment({transcriptPath:b,sessionId:k,conversationId:y,executionEnv:i}),C={};for(const[e,t]of Object.entries(_))void 0!==t&&(C[e]=t);void 0!==a&&(C.CURSOR_PLUGIN_ROOT=a,C.CLAUDE_PLUGIN_ROOT=a);const E=(0,be.q6)(),x=new Ic.StringDecoder("utf8"),P=new Ic.StringDecoder("utf8");let I,R="",T="",A=null,$=!1;for await(const e of this.shellExecutor.execute(E,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:C,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),$=!0);break;case"stdout":R+=x.write(e.data);break;case"stderr":T+=P.write(e.data);break;case"exit":A=e.code,I=e.aborted}if(R+=x.end(),T+=P.end(),m&&!$)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const M=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:R,stderr:T,exitCode:A,duration:M}}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,ti.rm)(d,{recursive:!0,force:!0})}catch{}}}}class HM{constructor(e){this.config=e,this.configuredSteps=xM.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var qM=r("node:perf_hooks");function zM(e,t){void 0!==e&&t.length>0&&e.push(...t)}class GM 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 VM=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function KM({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 GM({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new VM.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ke).map((e=>{if(!function(e){return e===Ce.sessionStart||e===Ce.beforeSubmitPrompt||e===Ce.preToolUse||e===Ce.postToolUse||e===Ce.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}]})));class JM extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZM extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XM="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QM(e,t){return We(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XM}`)}function YM(e){return function(e){return e instanceof JM}(e)||function(e){return e instanceof ZM}(e)}const eD=(0,x.h)("generic-hooks");function tD(e,t,r,n){try{return KM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof GM)return eD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rD=e=>Math.round(1e3*e)/1e3;function nD(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,Xs.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 vl(e.signal,(()=>t.executeHookForStep(Ce.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));zM(i,tD(e,r,Ce.postToolUseFailure,h?.additional_context))}catch(t){eD.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await vl(e.signal,(()=>t.executeHookForStep(Ce.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));zM(i,tD(e,r,Ce.postToolUse,u?.additional_context))}catch(t){eD.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 oD(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await vl(e.signal,(()=>r.executeHookForStep(Ce.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=We(r);try{zM(n.hookContextCollector,KM({hookEventName:Ce.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof GM))throw t;eD.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))),zM(n.hookContextCollector,KM({hookEventName:Ce.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Ce.preToolUse,s.toolName)??!1,c=n instanceof GM;if(a){const e=Ue(`${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}}eD.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(YM(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 sD(e){return e.toolCallId}function iD(e,t,r,n){return{async execute(o,s,i){const a=cD(o,t),{hookContext:c,helpers:l}=nD(o,s,a,r,n,i);let u;try{u=await oD(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=qM.performance.now();try{const t=await e.execute(o,s,i),r=rD(qM.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(YM(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eD.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=rD(qM.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aD(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cD(e,t){const r=Pt(e),n=e.get(Et);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===Ce.preToolUse||e===Ce.postToolUse||e===Ce.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 lD(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uD{async readFile(e){try{return await ti.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await ti.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,ti.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lD(e))return!0;throw e}return!1}(e,t)}}class dD{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 Lr.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 Lr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Lr._G({result:{case:"success",value:new Lr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function hD(e){return!!e&&e.type!==Hi.vc.INSECURE_NONE&&e.type!==Hi.vc.UNSPECIFIED}async function pD({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Ce.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QM("Command execution",i.user_message);throw new JM(e)}if("ask"===i?.permission)return a=i.user_message,new Ir.In({kind:Ir.b.FORCE_PROMPT,reason:a});var a}const fD={toolName:$M,getToolCallId:sD,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 xr.Lt({result:{case:"rejected",value:new Ir.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=hD(r.sandboxPolicy);It(t,Ce.beforeShellExecution)&&Wr(r,await pD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class mD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,fD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const gD={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new xr.nt({result:{case:"error",value:new xr.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 wD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,gD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const yD={toolName:"ComputerUse",getToolCallId:sD,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Mg.ks({result:{case:"error",value:new Mg.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 vD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,yD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const bD={toolName:RM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Pr.Pi({result:{case:"rejected",value:new Pr.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 SD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,bD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const kD={toolName:MM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new HI.Ek({result:{case:"rejected",value:new HI.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 _D{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,kD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const CD={toolName:"Fetch",getToolCallId:sD,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Uw.uN({result:{case:"error",value:new Uw.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 ED{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,CD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xD={toolName:AM,getToolCallId:sD,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 ay.Ud({result:{case:"error",value:new ay.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 PD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,xD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ID={toolName:TM,getToolCallId:sD,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 _I.fv({result:{case:"rejected",value:new _I.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 RD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,ID)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TD=(0,x.h)("hooks-exec:mcp");function AD(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(AD):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&AD(e))))}function $D(e,t,r,n){try{return KM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof GM)return TD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class MD{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(Ce.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Ce.beforeMCPExecution)))return new rr.iz({result:{case:"error",value:new rr.Nh({error:`"${pr}" 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=cD(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,Xs.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(Ce.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{zM(i,KM({hookEventName:Ce.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof GM))throw t;TD.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 rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:QM("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(!AD(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ar.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){TD.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}zM(i,KM({hookEventName:Ce.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Ce.preToolUse,c)??!1,l=t instanceof GM;if(r){const r=Ue(`${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 rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:QM("MCP tool execution",r),isReadonly:!1})}})}TD.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=It(e,Ce.beforeMCPExecution)?await n.executeHookForStep(Ce.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QM("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:t,isReadonly:!1})}})}const g=qM.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rD(qM.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){TD.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(Ce.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 rr._Z({content:{case:"text",value:new rr.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 rr._Z({content:{case:"text",value:new rr.zN({text:String(e.text)})}})):t.push(new rr._Z({content:{case:"text",value:new rr.zN({text:JSON.stringify(e)})}}))}else t.push(new rr._Z({content:{case:"text",value:new rr.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new rr.iz({result:{case:"success",value:new rr.QW({content:t,isError:r})}})}catch(t){return TD.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rD(qM.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(Ce.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return zM(c,$D(e,n,Ce.postToolUse,l?.additional_context)),l}catch(t){return void TD.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(Ce.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});zM(u,$D(e,n,Ce.postToolUseFailure,d?.additional_context))}catch(t){TD.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const DD={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new rr.kP({result:{case:"error",value:new rr.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 OD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,DD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FD={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 rr.ZD({result:{case:"error",value:new rr.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 ND{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,FD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jD={toolName:PM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new nr.sV({result:{case:"rejected",value:new nr.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?.(Ce.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${XM}`}(t,e instanceof Error?e.message:String(e));throw new ZM(r,e)}}((()=>o.executeHookForStep(Ce.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QM("File read",a.user_message);throw new JM(e)}}};class LD{constructor(e,t,r){this.wrappedExecutor=new ur(iD(e,t,r,jD))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UD={toolName:"RecordScreen",getToolCallId:sD,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new FR.Tj({result:{case:"failure",value:new FR.yH({error:t})}}),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 BD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,UD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function WD(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const HD={toolName:$M,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 Ir.W4({result:{case:"rejected",value:new Ir.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:WD(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||"";It(t,Ce.beforeShellExecution)&&Wr(r,await pD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:hD(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=WD(r);await o.executeHookForStep(Ce.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:hD(t.requestedSandboxPolicy),tool_use_id:i})}};class qD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,HD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class zD{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 GD={toolName:$M,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 Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Ir.FI({event:{case:"hookContext",value:new Ir.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new zD,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=hD(r.requestedSandboxPolicy);It(t,Ce.beforeShellExecution)&&Wr(r,await pD({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=hD(t.requestedSandboxPolicy);await n.executeHookForStep(Ce.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class VD{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cD(o,t),{hookContext:c,helpers:l}=nD(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oD(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aD(n,c))yield e;return}const h=qM.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=rD(qM.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aD(n,c))yield e;throw e}const f=rD(qM.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){eD.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 aD(n,c))yield e}}}(e,t,r,GD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class KD{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iD(e,t,r,function(e){return{toolName:IM,getToolCallId:sD,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 Rr.v3({result:{case:"error",value:new Rr.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?.(Ce.afterFileEdit))return;let s,i=!1;try{(await(0,ti.stat)(r.path)).size>262144?i=!0:s=await ac(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?.(Ce.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,ux.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(Ce.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ac(e),r=wa(t),o=Buffer.byteLength(t,"utf8");return new Rr.v3({result:{case:"success",value:new Rr.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 JD(e,t,r){return t===e.symbol}function ZD(e,t,r){return JD(Tr,e)?new qD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Ar,e)?new VD(t,r.hookExecutor,r.baseHookRequestExtractor):JD($r,e)?new KD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Kt,e)?new MD(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):JD(dr,e)||JD(hr,e)?new LD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Ft,e)?new RD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(_e,e)?new PD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Se,e)?new ED(t,r.hookExecutor,r.baseHookRequestExtractor):JD(ye,e)?new SD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(ve,e)?new _D(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Jt,e)?new OD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Zt,e)?new ND(t,r.hookExecutor,r.baseHookRequestExtractor):JD(de,e)?new mD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(he,e)?new wD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(we,e)?new vD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Nr,e)?new BD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(jr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new dD(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class XD{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===Rt.symbol)return new Dt(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ZD(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=ZD(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=Rt;yield[e,new Dt(this.hookExecutor)]}}const QD={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function YD(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>YD(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,oi.oG)(),args:[...pt,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,kl.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}}}function eO(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function tO(e){return"string"==typeof e&&e.length>0?e:void 0}function rO(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function nO(e){if(Array.isArray(e)&&e.every(rO))return e.map((e=>({id:e.id,value:e.value})))}class oO{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 sO(e,t={}){const r=await new xM(new uD,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?_M():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 HM(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...QD,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new WM(r,i,a,(t.createTerminalExecutor??YD)(),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 iO(e={}){return{createHooksRuntime:t=>sO(t.workspaceState,e)}}var aO=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function cO(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function lO(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 sy,l=(0,o.homedir)(),u=km(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,Fn.createClient)(aO.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await GA(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return KA.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,be.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new e$.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:gO(),getAgentSkills:async e=>[]};const p=(0,be.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new yg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=uO(t);return{getAllCursorRules:async t=>dO(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?gO():1===m.length?m[0]:new wg(m,(()=>Um)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=uO(t);return{getAllCursorRules:async t=>dO(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>dO(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new vg(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 Rg(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),b=R$(o.services.pluginBootstrapOutputs),S=b&&a?new Sg(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new $g((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,_=new wg([g,w,...S?[S]:[]],(()=>Um)),C=new AA([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),E=new Ag([v,...k?[k]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:S,pluginSubagentsService:k,mergedCursorRulesService:_,mergedAgentSkillsService:C,mergedSubagentsService:E};const x={cursorRulesService:_,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:E};return x},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 cO(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function uO(e){const t=Promise.all(e.allowedRoots.map(fO)),r=Promise.all(e.excludedRoots.map(fO));return async e=>{const[n,o,s]=await Promise.all([mO(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>hO(n,e)))&&o.some((e=>hO(n,e)))}}async function dO(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function hO(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function pO(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function fO(e){try{return pO(await(0,ti.realpath)(e))}catch{return pO(e)}}async function mO(e){try{return pO(await(0,ti.realpath)(e))}catch{return}}function gO(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function wO(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":d$.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":d$.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){d$.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=yO(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 lm(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,Fn.createClient)(aO.I,e.dashboardTransport),n=Wp((async()=>{try{return await r.getEffectiveUserPlugins(new e$.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Wp((async()=>{if(void 0===o)return{plugins:[]};try{const e=await lm(o);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||om(t)})).map((({key:e,entry:t})=>{const r=um(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 i=[];if(n.length>0)try{const e=n.map((e=>{const t=um(e.key);return new e$.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new e$.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new ph(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new ph(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=yO(d),p=new YA(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:I$,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)d$.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)d$.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 yO(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class vO{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const bO=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function SO(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 kO(e){const t=SO(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function _O(e){const t=SO(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 CO(e){const t=kO(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>kO(t.host).length-kO(e.host).length));for(const e of r){const r=kO(e.host);if(t===r)return _O({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return _O({reportedWorkspacePath:e.reported,suffix:n})}}}const EO={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class xO extends _A{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await cO(this.sessionMcpLease)}}}function PO(e){const t=new sy;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 vO,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new h_,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 h_:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Lw(u,d):new jw(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 EO;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return EO}}(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),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 _A(u):new xO(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(jr);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(jr,{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=>CO({value:e,roots:o})??e));for(const e of bO){const t=n[e];if(void 0===t||""===t)continue;const r=CO({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??SO(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 cO(c),e}}}}const IO=["cursorRulesService","getAgentSkills","subagentsService"],RO=new WeakSet;function TO(e){("object"==typeof e&&null!==e||"function"==typeof e)&&RO.add(e)}function AO(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&RO.has(e)}function $O(e,t){const r=Object.keys(t).filter((e=>!IO.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${IO.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of IO)Object.hasOwn(t,r)&&(e[r]=t[r])}async function MO(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&&(TO(s.cursorRulesService),TO(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&$O(n,e)}return n}catch(t){try{await DO(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 DO(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await cO(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||AO(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||AO(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 cO(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 OO=["project","user","team","mdm","plugins"],FO=new Set([...OO,"all"]);function NO(e){if(void 0===e||0===e.length)return LO([]);for(const t of e)if(!FO.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{...LO(OO),all:!0}}return LO(e.filter((e=>"all"!==e)))}function jO(e,t){return e[t]}function LO(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 UO=Object.freeze({}),BO=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:UO});async function WO(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 cO(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function HO(e={}){const t=function(e={}){return{workspace:e.workspace??c$,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({...BO.metadata,...e.metadata}),r={...BO,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await MO(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,On.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 WO(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 WO(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 MO(t,r,n);s?await DO(i,{disposeLocalExtensibility:l}):(o=i,await DO(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await DO(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class qO{async requestApproval(e){return{approved:!0}}}class zO{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 GO{async open(e,t){}async getDiagnostics(e,t){return[]}}class VO{async getCodebaseReference(e,t){}}class KO{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class JO{constructor(e){this.subagents=e.map((e=>new yn.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:yn.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}let ZO;function XO(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return ei(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,Qs.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,ni.statSync)(e).isDirectory()&&((0,ni.accessSync)(e,ni.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,Qs.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,Qs.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===ZO&&(ZO=function(e){return(0,ni.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),ZO)})}async function QO(e,t){const r=(0,s.dirname)(e);await(0,ti.mkdir)(r,{recursive:!0}),await(0,ti.writeFile)(e,t,"utf-8")}class YO{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=XO(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=z$({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new SM(this.projectDir,e.blobStore,QO,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new SM(this.projectDir,e.blobStore,QO,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=z$({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){d$.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,$n.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=z$({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=z$({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(XO(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const eF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,tF="User aborted/interrupted manually.";class rF{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.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,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 _n}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(!eF.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&Cn(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,On.C)(),o=function(e){const t=new $n.We,r=(0,$n.sh)(e),n=new $n.pH(new $n.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 YO({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:yn.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:yn.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 wn.a3({status:wn.jh.ACCEPTED}):new wn.a3({status:wn.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){d$.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 wn.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,On.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}async executeSubagentOnce(e,t,r,n){let o,s=0;const i=new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:r.prompt})})}}),a=new Gr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new u$,l={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&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return rn(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return on(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return cn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Do.tz({result:{case:"rejected",value:new Do.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return sn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},u={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const d=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==d&&""!==d?d:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new oe(f,function(e){const t=[te($r,Dr(e.errorMessage)),te(ye,Or(e.errorMessage)),te(Kt,Fr(e.errorMessage))];return e.wrapShell&&t.push(te(Tr,function(e){return{execute:async(t,r)=>new Ir.W4({result:{case:"permissionDenied",value:Mr(e,r)}})}}(e.errorMessage)),te(Ar,function(e){return{async*execute(t,r){yield new Ir.FI({event:{case:"permissionDenied",value:Mr(e,r)}})}}}(e.errorMessage)),te(de,function(e){return{execute:async(t,r)=>new xr.Lt({result:{case:"permissionDenied",value:Mr(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(te(he,function(e){return{execute:async(t,r)=>new xr.nt({result:{case:"error",value:new xr.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})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),i,a,l,m,n.agentStore.getBlobStore(),c,u,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:p$(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:tF}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return d$.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:tF}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:tF}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!Cn(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 wn.zJ({result:{case:"stillRunning",value:new wn.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 wn.zJ({result:{case:"complete",value:new wn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new wn.zJ({result:{case:"error",value:new wn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new wn.zJ({result:{case:"stillRunning",value:new wn.L5({agentId:r})}}):new wn.zJ({result:{case:"notFound",value:new wn.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 wn.zJ({result:{case:"stillRunning",value:new wn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new wn.zJ({result:{case:"complete",value:new wn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new wn.zJ({result:{case:"error",value:new wn.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 nF=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),oF=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),sF=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),iF=r("./src/agent/analytics.ts"),aF=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const cF={[Mg.w3.UNSPECIFIED]:"unspecified",[Mg.w3.LEFT]:"left",[Mg.w3.RIGHT]:"right",[Mg.w3.MIDDLE]:"middle",[Mg.w3.BACK]:"back",[Mg.w3.FORWARD]:"forward"},lF={[Mg.Dh.UNSPECIFIED]:"unspecified",[Mg.Dh.UP]:"up",[Mg.Dh.DOWN]:"down",[Mg.Dh.LEFT]:"left",[Mg.Dh.RIGHT]:"right"},uF={[Mg.EB.UNSPECIFIED]:"unspecified",[Mg.EB.TAP]:"tap",[Mg.EB.DOWN]:"down",[Mg.EB.UP]:"up"};function dF(e){return cF[e]??"unspecified"}function hF(e){return void 0===e?void 0:{x:e.x,y:e.y}}function pF({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:hF(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 fF(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 mF("tool-call-started",e.message.value);case"partialToolCall":return mF("partial-tool-call",e.message.value);case"toolCallCompleted":return mF("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"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=fF(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"modelCallCompleted":case void 0:return null;default:return e.message,null}}function mF(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:SF(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:kF(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:_F(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:CF(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:xF(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:PF(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:IF(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:TF(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:AF(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:MF(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:DF(t.mode)},...r?{result:OF(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:$F(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:FF(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:jF(e.status)})))},...r?{result:NF(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:hF(e.value.coordinate)};case"click":return{type:"click",coordinate:hF(e.value.coordinate),button:dF(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:dF(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:dF(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:hF(e.value.coordinate),direction:lF[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:uF[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?pF(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:gF(t),...r?{result:vF(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"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":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 gF(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:wF(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:yF(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function wF(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function yF(e){switch(e){case yn.FL.AGENT:return"agent";case yn.FL.PLAN:return"plan";default:return"unspecified"}}function vF(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:bF(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function bF(e){switch(e){case yn.qL.AGENT_REQUEST:return"agentRequest";case yn.qL.USER_REQUEST:return"userRequest";case yn.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function SF(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 kF(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 _F(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 CF(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]=EF(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:EF(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function EF(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 xF(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 PF(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 IF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:RF(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RF(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(RF)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function TF(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:LF(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 AF(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 $F(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 MF(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 DF(e){switch(e){case FR.$u.START_RECORDING:return"START_RECORDING";case FR.$u.SAVE_RECORDING:return"SAVE_RECORDING";case FR.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function OF(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 FF(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 NF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:jF(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function jF(e){switch(e){case aF.Vj.UNSPECIFIED:case aF.Vj.PENDING:return"pending";case aF.Vj.IN_PROGRESS:return"inProgress";case aF.Vj.COMPLETED:return"completed";case aF.Vj.CANCELLED:return"cancelled";default:return"pending"}}function LF(e){switch(e){case HI.h_.UNSPECIFIED:case HI.h_.ERROR:return"error";case HI.h_.WARNING:return"warning";case HI.h_.INFORMATION:return"information";case HI.h_.HINT:return"hint";default:return"error"}}const UF={type:"object",properties:{},additionalProperties:!0};function BF(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function WF(e){return"text"===e.type?new rr._Z({content:{case:"text",value:new rr.zN({text:e.text})}}):new rr._Z({content:{case:"image",value:new rr.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function HF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var qF=r("./src/agent/errors.ts");const zF="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 GF(e){return{async execute(){throw new Error(e)}}}function VF(e){var t;e.register(Tr,GF(zF)),e.register(Ar,(t=zF,{async*execute(){throw new Error(t)}})),e.register(de,GF(zF)),e.register(Br,GF(zF)),e.register(he,GF(zF)),e.register(Er,GF(zF)),e.register(ve,GF("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(ke,GF("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var KF=r("./src/agent/filesystem/executors.ts"),JF=r("./src/agent/filesystem/compose.ts"),ZF=r("./src/agent/filesystem/trees.ts"),XF=r("./src/agent/filesystem/walk.ts");const QF="/tmp",YF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function eN(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,XF.eI)(e.hostProjectDir),r=(0,XF.eI)(e.writePath);return"/"!==t&&(0,XF.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,XF.eI)(e.writePath):(0,XF.eI)(`${QF}/${r}`);if(!(0,XF.hJ)({path:n,prefix:QF}))return;const o=a().posix.basename(n),s=a().posix.join(QF,ml);return a().posix.dirname(n)===s&&YF.test(o)?a().posix.join(QF,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 tN{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,XF.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([rN(e,s.posix.join(t,".cursor/rules")),nN(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 rN(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,ir.PH)(r,(async t=>{const r=await oN(e,t),n=void 0===r?null:k(r);if(null!==n)return gg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function nN(e,t){const r=await oN(e,t);if(void 0!==r)return gg({path:t,body:b({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function oN(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const sN={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},iN={async exec(){throw new Error("git is not available in a FileSystem session")}},aN={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function cN(e){return{cursorRulesService:!0===e.includeProjectRules?new tN(e.fs,e.workspace):sN,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:iN,ignoreService:aN,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function lN(e,t){const r=t.workspace??"/",n=(0,KF.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:eN({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...cN({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:QF,excludeHooks:!0,excludeProjectMcp:!0}}var uN=r("./src/agent/executor-common.ts"),dN=r("./src/agent/native/vendored-tree-sitter.ts"),hN=r("./src/agent/platform-package-locator.ts"),pN=r("./src/agent/sdk-config.ts"),fN=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),mN=r("./src/agent/utils/logger.ts");const gN={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},wN=new Map;async function yN(e){try{const t=await async function(e){const t=await(0,uN.dC)(e,uN.EV);if(!t)return;const r=uN.EV.endsWith("/")?uN.EV.slice(0,-1):uN.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,uN.tF)(),"x-ghost-mode":(0,uN.U)(e)},body:JSON.stringify({})});if(!n.ok)return void mN.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return vN(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return gN;const r=new fN.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(vN(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,uN.tF)()}}}catch(e){mN.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,uN.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 mN.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),gN}}function vN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function bN(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var SN=r("./src/agent/tools-option.ts");class kN{async requestApproval(){return{approved:!0}}}function _N(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof _A))throw new qF.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Kt),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Lt}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new rr.iz({result:{case:"error",value:new rr.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:HF(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ar.Struct.fromJson(t.structuredContent):void 0;return new rr.iz({result:{case:"success",value:new rr.QW({content:t.content.map(WF),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 rr.iz({result:{case:"error",value:new rr.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new kN;e.resources.base.register(Kt,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Lt}(t)){const o=await hE(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 CN=new Set(["127.0.0.1","localhost","[::1]"]);function EN(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function xN(){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 PN={warn(){},error(){}},IN={log(){}};class RN{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${TN(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 TN(e){switch(e.type){case Ow.Shell:return"this shell command";case Ow.Mcp:return"this MCP tool call";case Ow.Write:return"this file edit";case Ow.Delete:return"this file deletion";default:return"this operation"}}function AN(e){return void 0!==e&&"insecure_none"!==e.type}async function $N(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,be.q6)().with(x._O,IN),a=NO(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&&CN.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}`);Uc=e}((0,pN.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(uN.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let d=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,uN.ly)(r.apiKey),(0,uN.mU)(r.apiKey)]),d=performance.now()-e}const h=r.workingDirectory||process.cwd();(0,dN.configureVendoredTreeSitterWorkspaceDir)(h);for(const e of r.dirs??[])(0,dN.configureVendoredTreeSitterWorkspaceDir)(e);const p=(0,Qs.Rv)((0,o.homedir)(),h),f={hostProjectDir:p,settings:{includeProjectRules:jO(a,"project"),subagentsService:new JO(r.customSubagents??[])}};let m;const g="win32"===process.platform?"rg.exe":"rg",w=process.env.CURSOR_RIPGREP_PATH;m=w&&(0,s.isAbsolute)(w)?w:(0,hN.hQ)({binaryName:g,excludedWorkspaceDir:h}),m||(m=(0,oi.xS)()),m&&(0,oi.J)(m);let y,v,b={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{y=(0,uN.KU)(r.apiKey,r.teamId);const e=(0,Fn.createClient)(aO.I,y),t=function(e){let t=wN.get(e);return t||(t=yN(e),wN.set(e,t),t.then((r=>{r===gN&&wN.get(e)===t&&wN.delete(e)}),(()=>{wN.get(e)===t&&wN.delete(e)}))),t}(r.apiKey);v=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};b=new i$(new n$(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===l?{}:{hostMcpBridgeUrls:l},isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){mN.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const S=performance.now(),k=r.apiKey?await(0,oi.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,_=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=AN(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,oi.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,hN.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,oi.St)({sandboxBinaryPath:r})}(t),!(0,oi.K3)(void 0,{ctx:e.initializationCtx}))throw new qF.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,oi.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:h,perUserSandboxPolicy:k,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,C=performance.now()-S,E=_?.defaultSandboxPolicy,P=_?.defaultSandboxPolicySources,I=AN(E),R=performance.now(),T=(()=>{const e=[],t=new Set;for(const n of[h,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),A={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},$=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=NO(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,oi.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new sy,h=new dl(d,a,n),p=new GO,f=new VO,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new zO(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=jO(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=_||jO(i,"project")||jO(i,"user")||b,x=jO(i,"project")||jO(i,"user")||jO(i,"mdm"),P=jO(i,"team"),I=P&&void 0!==e.dashboardTransport,R=jO(i,"project")||jO(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:jO(i,"project"),includeUserMcp:jO(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>HO({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:D$({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:wO({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:iO({includeProjectHooks:jO(i,"project"),includeUserHooks:jO(i,"user"),includeEnterpriseHooks:jO(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:lO({includeProjectExtensibility:jO(i,"project"),includeUserExtensibility:jO(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:PO({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=>new KO(new aT(e)),createSessionMcpLease:(t,r)=>D$({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{const r=w??new qO;return{pendingDecisionStore:r,fileChangeTracker:new Hw(t),permissionsService:new fP(h,r,g,a,t,e.respectAdminControls??!1)}}}),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 oO(new XD(e.resources,n.hookExecutor,(()=>function(e,t){const r=eO(t,tO,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:eO(t,tO,"generationId","generation_id")??r,model:eO(t,tO,"model")??"unknown",...Ve({modelId:eO(t,tO,"modelId","model_id"),modelParams:eO(t,nO,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new JO(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 d$.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:h,...void 0!==T?{dirs:T}:{},projectDir:p,teamSettingsService:b,initializationCtx:i,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:E,defaultSandboxPolicySources:P,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new RN:void 0,getNetworkAllowlistInfo:I?()=>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,oi.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,oi.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(b,(0,o.homedir)(),h):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:xN,getPowershellUtf8Options:async()=>{if(void 0===v)return A;try{const e=await v;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return A}},isLinkSharedPaymentTokenLogRedactionEnabled:bN(v),respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),M=performance.now()-R;let D,O;return(0,iF.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(d),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(M),load_sandbox_policy_ms:Math.round(C),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,d$.ni)(PN,(async()=>{const s=(0,c.VI)((0,be.q6)().withName("sdk.run").with(x._O,IN)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,On.C)(),u=t.mcpServersOverride,d=void 0===(p=t.customTools)?[]:Object.entries(p).map((([e,t])=>({clientKey:Lt,providerIdentifier:Lt,toolName:e,name:`${Lt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??UF,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:BF(t.annotations)},source:"internal"})));var p;let m;const g={...f,workspace:t.fileSystemWorkspace},w=void 0===t.fileSystem?void 0:(y=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),v=y,(0,JF.VL)({"/":v,[QF]:(0,ZF.Om)()}));var y,v;m=await $.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:d,...void 0===w?EN(t.sessionResources):lN(w,g)});const b=new Map;try{const s=m.resources.wrapped;_N(m,t.customTools),void 0!==w&&VF(m.resources.base);const c=t.blobStore??new $n.ve;let p=t.initialState??new Gr.Y9z({});const f=void 0!==t.model?new oF.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new oF.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,v=Array.isArray(y)?y.map((e=>{const t=(0,On.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,uN.v8)(r);return new sF.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=v.length>0?new sF.xv({selectedImages:v}):void 0,C=function(e){switch(e){case"agent":return Gr.xyI.AGENT;case"plan":return Gr.xyI.PLAN;default:return}}(t.mode),E=!0===e.summarize?new Gr.QFf({action:{case:"summarizeAction",value:new Gr.Scs}}):new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:e.text,selectedContext:_,...void 0!==C?{mode:C}:{}})})}}),x={sendUpdate:async(e,t)=>{const r=fF(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return tn(e.id);case"webFetchRequestQuery":return nn(e.id);case"switchModeRequestQuery":return an(e.id);case"askQuestionInteractionQuery":return sn(e.id,new Do.tz({result:{case:"rejected",value:new Do.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return ln(e.id,new Kr.bK({result:{case:"success",value:new Kr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return un(e.id,new No.r$({result:{case:"success",value:new No.JH}}));case"replaceEnvArgs":return dn(e.id,new Fo.dV({result:{case:"failure",value:new Fo.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return hn(e.id,new Oo.HL({result:{case:"error",value:new Oo.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return pn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return fn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return mn(e.id,e.query.value.args?.description);case void 0:throw new qF.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new qF.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(D!==t.apiKey||!O){await Promise.all([(0,uN.ly)(t.apiKey),(0,uN.mU)(t.apiKey)]);const e=(0,uN.KU)(t.apiKey,r.teamId),n=Zs((0,Fn.createClient)(nF.N,e),{injectTraceHeaders:!0});O=new Ws(n),D=t.apiKey}const P=(0,uN.Vh)(O,(()=>{const e=(0,uN.KU)(t.apiKey,r.teamId),n=Zs((0,Fn.createClient)(nF.N,e),{injectTraceHeaders:!0}),o=new Ws(n);return O=o,D=t.apiKey,o})),I=function(e){return{...void 0!==e.allowedTools?{[SN.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[SN.VJ]:e.disallowedTools.join(",")}:{}}}(t),R=new rF({agentClient:P,getResources:async({agentId:e})=>{let r=b.get(e);return r||(r=await $.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:d,...void 0===w?EN(t.subagentInherit):lN(w,g)}),_N(r,t.customTools),void 0!==w&&VF(r.resources.base),r.resources.base.register(bn,T),r.resources.base.register(Sn,A),r.resources.base.register(kn,M),b.set(e,r)),r.resources.wrapped},mcpTools:d,workspacePath:h,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==w)&&Object.keys(I).length>0?{headers:I}:{},onSessionReleased:e=>{const t=b.get(e);t&&(t.dispose(),b.delete(e))}}),T=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 wn.vS({result:{case:"error",value:new wn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new wn.vS({result:{case:"error",value:new wn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new wn.vS({result:{case:"success",value:new wn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new wn.vS({result:{case:"success",value:new wn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof en)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof vn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new wn.vS({result:{case:"error",value:new wn.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}}}(R),A=(k=R,{execute:(e,t)=>k.awaitBackgroundRunBounded(e,t)}),M=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(R);m.resources.base.register(bn,T),m.resources.base.register(Sn,A),m.resources.base.register(kn,M);const F=$.services.hooksRuntime,N="object"==typeof(S=F)&&null!==S&&"workspacePath"in S&&"string"==typeof S.workspacePath&&"createSessionRuntime"in S&&"function"==typeof S.createSessionRuntime?F:void 0,j=void 0!==N&&void 0===w&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Ce.sessionStart)||t.hooksConfigLease.hasHookForStep(Ce.sessionEnd)||t.hooksConfigLease.hasHookForStep(Ce.stop)||t.hooksConfigLease.hasHookForStep(Ce.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(Ce.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),is_background_agent:!1},r=await n.executeHookForStep(Ce.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){d$.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Ce.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?Ve(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Ce.sessionEnd,r)}catch(e){d$.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Ce.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Ce.beforeSubmitPrompt,t)}catch(e){d$.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Ce.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Ce.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(Ce.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Ce.stop,t)}catch(e){d$.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Ce.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Ce.stop,t)}catch(e){d$.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:N,sessionState:m.state,metadata:m.metadata}):void 0,L=new YO({workspacePath:h,conversationId:l,blobStore:c}),U=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new u$;let a;const c=new Map,l=(e,t)=>{const r=c.get(e);void 0!==r&&(c.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let u;const d=[],h=e=>{for(const t of d.splice(0))t.resolve(e)},p=()=>{if(0===d.length)return;const e=d.map((e=>e.text)).join("\n\n");return h("complete_delivered"),w$(e)},f=r.interactionListener,m={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:c.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):(c.delete(t),s.resolve(e))}}await f.sendUpdate(e,t)},query:(e,t)=>f.query(e,t),...void 0!==f.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>f.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==f.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>f.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let g=r.initialState;const w={async handleCheckpoint(e,t){g=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>g};let y="completed";const v=Date.now(),b=p$(function(e,t){if((0,$n.TU)(t))return t;const r=f$.get(e);if(void 0!==r)return r;const n=(0,$n.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return f$.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=g$(r,0,m$(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw y="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==y)throw e;d$.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,d=0;for(;s;){const e=g$(r,d,m$(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){d$.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,On.C)();try{await r.agentClient.run(o,g,s,void 0,m,r.resources,r.blobStore,i,w,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:b,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw y=y$(t)?"aborted":"error",v$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...c.keys()])l(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw y="error",e}const f="string"==typeof t?t.trim():"";let v;if(f.length>0)v=w$(f);else{const t=new AbortController;u=t;try{v=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw y=o.signal.aborted||y$(r)?"aborted":"error",v$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{u=void 0}void 0===v?v=p():h("revert_to_followup")}void 0!==v?(d+=1,i.resetStream(),s=v):s=void 0}})().finally((async()=>{h("revert_to_followup");const e=Date.now()-v;try{await(n?.onSessionEnd?.(y,e))}catch(e){d$.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){d$.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=u;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{d.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,On.C)(),n=new Promise((e=>{const t=setTimeout((()=>{l(r,"revert_to_followup")}),15e3);t.unref?.(),c.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new Gr.QFf({action:{case:"injectContextAction",value:new Gr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new Gr.oW$({userMessage:new Gr.RGk({messageId:(0,On.C)(),text:e})})}})}})),await n}catch(e){return l(r,"revert_to_followup"),d$.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,E,{agentClient:P,interactionListener:x,resources:s,blobStore:c,initialState:p,conversationId:l,mcpTools:d,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:f,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(I).length>0?{headers:I}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:j,async nextAction(e,t){const r=await R.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new Gr.QFf({action:{case:"backgroundTaskCompletionAction",value:new Gr.Kwc({completions:e.map((e=>new Gr.KFq({taskId:e.agentId,kind:Gr.aZc.SUBAGENT,status:"success"===e.status?Gr.uHL.SUCCESS:"aborted"===e.status?Gr.uHL.ABORTED:Gr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){p=e,L.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),B=U.done.finally((async()=>{try{await R.awaitBackgroundWorkers()}finally{await L.waitForPendingWrites().catch((()=>{}));for(const e of b.values())try{await e.dispose()}catch(e){mN.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}b.clear(),await m.dispose()}})).catch((e=>{throw e}));return{abort(){U.abort(),a()},done:B,steer:e=>U.steer(e)}}catch(e){for(const e of b.values())try{await e.dispose()}catch{}throw b.clear(),await m.dispose(),e}var S,k})),async reload(){await $.reload()},async dispose(){await $.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)},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>q,ME:()=>L,_N:()=>H,b6:()=>j,bi:()=>P,mD:()=>A,vc:()=>O});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=F(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<=I&&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}}(F(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=F(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=F(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=F(e);return v.test(t)||function(e){const t=F(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=F(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=F(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(R.has(e))return R.get(e);R.size>=I&&R.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=`${F(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 R.set(e,t),t}const I=2048,R=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("*")&&F(s)===F(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=N(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!F(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(F(r.hostname)!==F(o))return}return r}}function O(e,t){if(A(e,t))return!0;let r;return T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=N(t),T.set(t,r)),!!r&&h(r.hostname,e)}function F(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function N(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 j(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function L(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=j(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(F(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 U(e){const t=e?.trim();return t&&t.length>0?t:void 0}function B(e){return U(e)?.toLowerCase()}function W(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function H({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=U(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=>function(e,t){const r=B(e.builtinServer),n=B(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=U(e.command),s=U(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&&O(s,t.url);return i&&a}(e,t)))}(c,t),d=W(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||W(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!==U(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!==U(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:()=>Yr,Ls:()=>d,SandboxUnsupportedError:()=>Ft,J:()=>_,St:()=>jt,Fn:()=>Qr,ue:()=>o,r5:()=>he,oG:()=>Rr,Ko:()=>P,CG:()=>je,W1:()=>V,G6:()=>Xr,_B:()=>Ie,OK:()=>xe,$b:()=>Pe,K3:()=>Bt,tv:()=>Oe,wG:()=>qe,fZ:()=>Ge,s9:()=>Ue,XX:()=>He,T6:()=>Te,Po:()=>Re,$6:()=>Me,l7:()=>Fe,xS:()=>k,resolveSandboxPolicyForWorkspace:()=>Je,spawnInSandbox:()=>Lt,Xw:()=>x});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function i(e){const t={...e};for(const e of s)delete t[e];return t}const a=[["core.quotePath","false"]];function c(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=y(e,r);if(p.existsSync(n))return v(n,t,r)}for(const o of n){const n=y(`${e}${o}`,r);if(p.existsSync(n))return v(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:h.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:h.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 b;const S=["/usr/local/bin","/usr/bin","/bin"];function k(){const e=v("rg",[]).cmd;return"rg"!==e?e:void 0}function _(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");b=e}function C(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 E(e,t){const r=(0,h.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=C(e);return void 0!==t?e[t]??"":""}(e).split(h.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=S),function(e,t){const r=C(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(h.delimiter))}function x(e){return b&&(0,h.isAbsolute)(b)?{...E(e,b),CURSOR_RIPGREP_PATH:b}:e}function P(){if(!b)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return b}const I="win32"===process.platform;function R(e){return!I&&!!e?.SUDO_ASKPASS}function T(e){return R(e)?"alias sudo='sudo -A'; ":""}function A(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 M=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function D(e){M.some((t=>$(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function O(e){$(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const F="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",N=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],j=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${N.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${F}";; esac; `,L=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${N.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${F}" } else { $env:MAVEN_OPTS = '${F}' }\n}`;var U=r("node:crypto"),B=r("node:os"),W=r("../utils/dist/workspace-paths.js"),H=r("../utils/dist/test-resets.js");let q;function z(e,t){const r=(0,p.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function G(e){try{(0,p.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function V(e){return K(e,{create:!1})}function K(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,h.join)((0,B.tmpdir)(),`cursor-sandbox-${(0,W.r_)((0,h.resolve)(e))}`);try{for(const e of[n,(0,h.join)(n,"tmp")])if(t&&G(e),!z(e,r))return;return n}catch{return}}(0,H.J)((function(){q=void 0}));const J='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function Z(e=(0,h.join)((0,B.tmpdir)(),"cursor-sandbox-cache",function(){return q||(q=(0,U.randomBytes)(16).toString("hex")),q}())){return{NPM_CONFIG_CACHE:(0,h.join)(e,"npm"),PNPM_STORE_PATH:(0,h.join)(e,"pnpm-store"),GOCACHE:(0,h.join)(e,"go-build"),GOMODCACHE:(0,h.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,h.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,h.join)(e,"pip"),UV_CACHE_DIR:(0,h.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,h.join)(e,"bun"),YARN_CACHE_FOLDER:(0,h.join)(e,"yarn"),npm_config_devdir:(0,h.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,h.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,h.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,h.join)(e,"turbo"),GRADLE_USER_HOME:(0,h.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,h.join)(e,"conda"),POETRY_CACHE_DIR:(0,h.join)(e,"poetry"),GEM_SPEC_CACHE:(0,h.join)(e,"gem-specs"),BUNDLE_PATH:(0,h.join)(e,"bundle"),COMPOSER_HOME:(0,h.join)(e,"composer"),HOMEBREW_CACHE:(0,h.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,h.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,h.join)(e,"nx"),NUGET_PACKAGES:(0,h.join)(e,"nuget"),CCACHE_DIR:(0,h.join)(e,"ccache"),CP_HOME_DIR:(0,h.join)(e,"cocoapods")}}var X=r("node:fs/promises"),Q=r("node:child_process"),Y=r("node:string_decoder"),ee=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),te=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class re extends Error{constructor(e,t,r,n,o,s){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=s,this.command=r,this.args=n,"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,re)}}function ne(e,t,r){r=r??{};let n=new ee.Observable((n=>{const{encoding:o,timeout:s,...i}=r,{cmd:a,args:c}=v(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const u=(0,Q.spawn)(a,c,i);r.processInfo&&void 0!==u.pid&&(r.processInfo.pid=u.pid);let d=null;s&&s>0&&(d=setTimeout((()=>{u.killed||u.kill();const e=new re(`Process timed out after ${s}ms`,-1,a,c);n.error(e)}),s));const h={stdout:new Y.StringDecoder(o||"utf8"),stderr:new Y.StringDecoder(o||"utf8")},p=t=>o=>{if(o.length<1)return;let s;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);try{s="string"==typeof o?o:h[t].write(o)}catch{s=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}s.length>0&&n.next({source:t,text:s})},f=e=>{const t=h[e].end();t.length>0&&n.next({source:e,text:t})},m=new ee.Subscription;if(l)if(u.stdin){const e=u.stdin;m.add(l.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let g=null,w=null,y=!1;if(u.stdout){const e=new ee.AsyncSubject;w=e,u.stdout.on("data",p("stdout")),u.stdout.on("close",(()=>{f("stdout"),e.next(!0),e.complete()}))}else w=(0,ee.of)(!0);if(u.stderr){const e=new ee.AsyncSubject;g=e,u.stderr.on("data",p("stderr")),u.stderr.on("close",(()=>{f("stderr"),e.next(!0),e.complete()}))}else g=(0,ee.of)(!0);return u.on("error",(e=>{y=!0,d&&clearTimeout(d),n.error(e)})),u.on("close",(e=>{y=!0,d&&clearTimeout(d);const t=(0,ee.merge)(w,g).pipe((0,te.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new re(`Process failed with exit code: ${e}`,e,a,c);n.error(t)}))})),m.add(new ee.Subscription((()=>{y||(d&&clearTimeout(d),u.kill())}))),m}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;n=n.pipe((0,te.L5)({count:e,delay:(e,r)=>{if(e instanceof re&&0!==e.exitCode)return(0,ee.timer)(t);throw e}}))}return r.split?n:n.pipe((0,te.Tj)((e=>e?.text)))}function oe(e,t,r){return r?.split?(n=ne(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof re){const n=new re(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof re){const t=new re(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(ne(e,t,{...r??{},split:!1}));var n}var se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const ie=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ae=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],ce=(e,t)=>t.flatMap((t=>ae.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),le={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},ue=e=>[...ie,...le[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),de=[{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"},...ue("linux"),...ce("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"},...ue("darwin"),...ce("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 he(e=process.platform,t=B.homedir(),r={}){const n=[];for(const o of de){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,h.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,p.lstatSync)(s).isFile();break;case"home-dir":e=(0,p.lstatSync)(s).isDirectory();break;case"bundled":e=(0,p.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const pe=[{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:"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"}];function fe(e){const t=pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function me(e){const t=pe.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}pe.filter((e=>"git"===e.type)).map((e=>e.pattern)),pe.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const ge=[];let we=null,ye=null;let ve=null;const be=new Map;const Se="win32"===process.platform||"darwin"===process.platform;function ke(e){if(!e.endsWith(h.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function _e(e){return e.endsWith(h.sep)?e:e+h.sep}function Ce(e,t){const r=ke(t);if(Se){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(_e(n))}return e===r||e.startsWith(_e(r))}function Ee(e,t){const r=ke(e);return Se?(0,h.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,h.relative)(r,t).replace(/\\/g,"/")}async function xe(e,t){if(Ce(e,t)){const r=Ee(t,e);if((null===we&&(we=se({ignoreCase:!0}),we.add(pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),we).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=be.get(e);if(t)return t;const r=await(0,X.stat)((0,h.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return be.set(e,t),t}const n=await async function(e){try{const t=await oe("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,h.dirname)((0,h.resolve)(e,t.trim()))}catch{return null}}(e),o={isWorktree:!0,gitDirParent:n??e};return be.set(e,o),o}(t);if(Ce(e,n)){const t=Ee(n,e);if((null===ye&&(ye=se({ignoreCase:!0}),ye.add(pe.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ye).ignores(t))return!0}if(r&&Ce(e,t)&&".git"===Ee(t,e))return!0;for(const t of function(){if(null!==ve)return ve;const e=B.homedir(),t=[];for(const r of pe)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,h.join)(e,r.pattern))}return ve=t,t}())if(Ce(e,t))return!0;return!1}function Pe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ie(e){return void 0!==e&&"allow"===e.default}function Re(){return{version:1,default:"deny"}}function Te(){return{version:1,default:"allow"}}var Ae=r("../utils/dist/path-utils.js");function $e(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 Me(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:$e(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function De(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","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 Oe(e,t){const r=await async function(e,t){try{const r=await(0,X.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==De(n))return{success:!1,error:`Invalid sandbox policy: ${De(n)??""}`};let o=Me(n);return t&&(o=Fe(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 Fe(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ae.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ae.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ae.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var Ne=r("../utils/dist/safe-spawn-cwd.js");function je(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Le(...e){return e.some((e=>!0===e))}function Ue(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ze(e));return[...t]}const Be=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]function(...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=ze(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ze);let r=new Set(t[0].map(ze));for(let e=1;en.has(e))))}return[...r]}(...e);function He(...e){return Be.merge(...e)}function qe(...e){return We(...e)}function ze(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Ge(...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 Ve(...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)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function Ke(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Je(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,Ne.$f)(e))return Ze(t,{workspaceDir:e});const n=r.stat??X.stat,o=r.spawnPromise??oe,s=await n((0,h.join)(e,".git")).then((e=>e),(()=>null)),i=s?.isFile()??!1,a=null!==s;if("workspace_readwrite"===je(t)){let r=e;if(i){const n=await o("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,h.resolve)(e,t.trim())),(()=>null));if(n){r=(0,h.dirname)(n);const o=t.perRepo,s=o?.ignoreMapping;t={...t,perRepo:{...o,type:"workspace_readwrite",additionalReadwritePaths:[...o?.additionalReadwritePaths??[],n],ignoreMapping:s,writeProtectionMapping:Ve(o?.writeProtectionMapping,me(e))}}}}if(a)return Ze(t,{workspaceDir:e,gitDirParent:r})}return Ze(t,{workspaceDir:e})}function Ze(e,t){return function(e,t){const r=function(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}(e);if(void 0===r)return tt({},t);switch(r){case"workspace_readwrite":return tt(Qe(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ye(e,t),o={policy:et({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,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Qe(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:et({type:"insecure_none",allowlistEscalated:Le(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Ke(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Le(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Ke(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Qe(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Xe(e,t){return e?.type===t}function Qe(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Xe(r,t)?r:void 0,perRepo:Xe(n,t)?n:void 0,teamAdmin:Xe(o,t)?o:void 0}}function Ye(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!==ge.length)return{version:1,deny:[...ge]}}(),r=B.homedir(),n=[];for(const e of pe)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,h.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:fe(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")},p=Le(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 f=Le(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=Ke(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=Ke(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?Ue(s.additionalReadPaths):Ue(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=Ue(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=Ge(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=Ke(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=Le(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=Ke(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=Ve(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=function(e){const t=pe.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??i);return{disableTmpWrite:p||void 0,networkPolicyStrict:f,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:Ve(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function et(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 tt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ye(e,t),a=Ue(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:et({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,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var rt=r("../utils/dist/workload-spawn.js"),nt=r("../context/dist/logger.js"),ot=r("../context/dist/core.js");const st=Q.execFile,it=new WeakMap;function at(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}let ct=0;function lt(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?h.resolve(e):h.resolve(h.join(B.homedir(),".cursor","sandbox-policies"))}();p.mkdirSync(e,{recursive:!0,mode:448});try{p.chmodSync(e,448)}catch{}const t=Date.now();return t-ct>=9e5&&(ct=t,function(e){let t;try{t=p.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=h.join(e,n);try{const e=p.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&p.unlinkSync(t)}catch{}}}(e)),e}function ut(e){const t=lt(),r=U.randomBytes(8).toString("hex"),n=h.join(t,`sandbox-policy-${r}`);return p.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const dt="darwin"===process.platform,ht="linux"===process.platform,pt=(0,nt.h)("shell-exec:sandbox");function ft(e){const t=lt();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let mt,gt=!0,wt=!1;function yt(){return mt}function vt(e){"linux"===process.platform&&Object.assign(e,x(e))}let bt=null,St=null,kt=null,_t=null,Ct=!1,Et=null;function xt(e){return{...e,additionalReadonlyPaths:ft(e.additionalReadonlyPaths)}}function Pt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return Mt(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,p.existsSync)(r)&&(0,p.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=function(e,t=e=>p.existsSync(e)){if((0,Ne.$f)(e))return!0;let r=h.resolve(e);for(;;){try{if(t(h.join(r,".git")))return!0}catch{}const e=h.dirname(r);if(e===r)return!1;r=e}}(r),s=!ht||o?t??{}:{},i={...n};for(const[e,t]of Object.entries(s))i[e]?i[e]=[...i[e],...t]:i[e]=t;if(0!==Object.keys(i).length)return Mt(i)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=gt;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=P()}catch{}for(const o of he(e,B.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=B.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=h.join(B.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=h.basename(e);if((o.includes("*")||o.includes("?"))&&(e=h.dirname(e)),!e||"."===e)continue;const s=h.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Pe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function It(e){const t={sandbox:e};return ht&&function(){const e=wt;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Rt(e){if(null!==bt)return bt;try{const t=yt();return pt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(bt=p.existsSync(t),bt?pt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(bt)}`):(St=new Error(`Sandbox binary not found at ${t}`),pt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),bt):(St=new Error("Sandbox binary path was not configured"),bt=!1,pt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return St=t instanceof Error?t:new Error(String(t)),bt=!1,pt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Tt(e){if(null!==_t)return _t;const t=e??(0,ot.q6)();if(pt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Rt(t)){const e=St?.message||"Binary check failed";return kt=e,pt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),_t=!1,_t}if("win32"===process.platform)return kt="Windows sandbox helper only provides network proxy, not filesystem isolation",pt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),_t=!1,_t;if("darwin"===process.platform)return kt=null,pt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),_t=!0,_t;const{binaryPath:r,args:n,env:o}=function(e,t){const r=It(Pt(xt({type:"workspace_readwrite"}),t)),n=String(yt());pt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),pt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return vt(o),{binaryPath:n,args:["--policy",ut(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,rt.D9)(Q.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:At,env:o,shell:!1});const s=Date.now()-e;return kt=null,pt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),_t=!0,_t}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return pt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),pt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&pt.error(e,`[sandboxPreflight] Stderr: ${o}`),kt=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"}`,_t=!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,H.J)((function(){_t=null,Ct=!1,Et=null,kt=null,bt=null,St=null}));const At=15e3;function $t(e,t=[],r={},n){const s=(0,ot.q6)();if(r.env=o(r.env),!Rt(s))throw new Error(`Sandbox binary not available: ${St?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,rt.D9)(Q.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let c=e,l=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",l=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",l=["-c",`${e} ${t.join(" ")}`]));const u=Pt(xt(n),a),d=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return K(e.cwd,{create:!0})}(u);d&&(u.additionalReadwritePaths=[...u.additionalReadwritePaths??[],d]);const p=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Pe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),f=It(u);void 0!==p&&(f.networkPolicy=p),!1===n.networkPolicyStrict&&(f.networkPolicyStrict=!1);const m=["--policy",ut(JSON.stringify(f)),"--",c,...l],g=o(process.env),w={..."linux"===process.platform?i(g):g,..."linux"===process.platform&&r.env?i(r.env):r.env,CURSOR_SANDBOX:"native"};if(vt(w),d){const e=function(e,t,r){const n=function(e){const t=(0,h.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,h.join)(t,"sh-")}}(e);if(r){const r=Z();for(const[o,s]of Object.entries(Z(e)))t[o]===r[o]&&(n[o]=s)}return n}(d,w,n.enableSharedBuildCache);Object.assign(w,e),w.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),w.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const y={cwd:r.cwd||s,env:w,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,rt.D9)(Q.spawn,String(yt()),m,y);return dt&&t.pid&&function(e,t){it.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,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function Mt(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Dt(t):t;o[e]=r;const n=Ot(e);n!==e&&(o[n]=r)}return o}function Dt(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ot(e,t){if((0,Ne.$f)(e))return e;try{return(t??p.realpathSync)(e)}catch{return e}}class Ft extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Nt="darwin"===process.platform;function jt(e){!function(e){P();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;mt||(mt=t),void 0!==r&&(gt=r),void 0!==n&&(wt=n)}(e)}function Lt(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...Z(),...r.env}}),"insecure_none"!==n.type){if(Tt())return $t(e,t,r,n);const o=kt;throw new Ft(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Q.spawn,spawnWorkload:rt.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function Ut(e){return Nt?async function(e){const t=it.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,rt.D9)(st,"/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:at(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:at(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 Bt(e,t){if(Nt)try{(0,p.accessSync)("/usr/bin/sandbox-exec",p.constants.X_OK)}catch{return!1}return Tt(t?.ctx)}var Wt=r("node:stream"),Ht=r("../context/dist/otel.js"),qt=r("../utils/dist/writable-iterable.js");const zt="--",Gt='builtin eval "$1" 3<&- 4>&-',Vt=50,Kt=262144;class Jt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Vt,this.maxBufferedBytes=t?.maxBufferedBytes??Kt}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 Jt(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([Xt(e.stdout,r,t),Qt(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 Xt(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 Qt(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Yt;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Yt||(Yt={}));const er={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function tr(e,t,r,n={spawn:Q.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function rr(e,t=[],r={},n,o){const s=Lt(e,t,{...r,env:x(r.env??process.env)},n);if(o){const e=function(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}({platform:process.platform,detached:!0===r.detached}),t=()=>{if(!s.pid)return;tr(s,e,"SIGTERM");const t=setTimeout((()=>{!s.killed&&s.pid&&tr(s,e,"SIGKILL")}),1e3);"process_group"!==e&&s.once("exit",(()=>{clearTimeout(t)}))};o.aborted?t():(o.addEventListener("abort",t,{once:!0}),s.once("exit",(()=>{o.removeEventListener("abort",t)})))}return s}function nr(e){const t=[];return e?.on("data",(e=>{t.push(e)})),()=>Buffer.concat(t).toString("utf8")}function or(e){e?.on("error",(()=>{}))}const sr="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 ir(e,t){return 126===e&&""===t}function ar(){return"win32"!==process.platform}function cr(e,t){const r=e.stdio.at(5);r instanceof Wt.Writable&&(or(r),r.end(`${t}\0`))}function lr(e,t){e&&(or(e),e.write(t),e.end())}function ur(e,t){if(!e)return;or(e);const r=new Y.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 dr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function hr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function pr(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 fr="__CURSOR_BASH_STATE_START__",mr="__CURSOR_BASH_STATE_END__";var gr=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 wr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=v("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:v("bash",[]).cmd}function yr(e){if("win32"!==process.platform)return e;const t=h.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===h.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function vr(e){const t=e.pipeStdin?Gt:`${Gt} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?sr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+J+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class br{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new br(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;h.resolve(t)===h.resolve(this.cwd)&&(this.cwd=void 0===r||h.resolve(r)===h.resolve(t)||(0,Ne.A)(r)?(0,Ne.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{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}(n,(0,Ht.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,qt.Jt)(),a=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...er,...e?.env};return c(n),"win32"===t&&(D(n),O(n)),n}(r),u=T(l),d=this.useFileStateTransport,p=!d&&!this.commandPipeUnreadable;let f,m,g;if(d){f=await(0,X.mkdtemp)(h.join(B.tmpdir(),"cursor-bash-state-")),m=h.join(f,"state-in"),g=h.join(f,"state-out"),await(0,X.writeFile)(m,this.state,"utf8"),await(0,X.writeFile)(g,"","utf8").catch((()=>{}));const e=yr(m),t=yr(g);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const w=function(e){return["-O","extglob","-c",e.script,zt,...void 0===e.command?[]:[e.command]]}({script:vr({pipeCommand:p,useFileTransport:d,sudoAliasInjection:u,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?j:""}),command:p?void 0:t}),y=wr(this.userTerminalHint);if(!y)throw new Error("Can't find Bash");const v=r?.sandboxWorkspaceRoot??a,b=(await Je(v,r?.sandboxPolicy)).policy,S="insecure_none"!==b.type?{...b,sandboxWorkspaceRoot:v}:b;let k="";const _=async()=>{if(d){if(!g)return void(k=this.state);try{k=await(0,X.readFile)(g,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),k=this.state}}},C=async()=>{if(f)try{await(0,X.rm)(f,{recursive:!0,force:!0})}catch{}};let E;(0,Ne.$Y)(a)&&(0,Ht.HF)(o.ctx,Ne.yo);try{E=rr(y,w,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:a,detached:!0},S,r?.signal)}catch(e){throw await C(),e}E.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:E.stdin??void 0,pid:E.pid})}catch(e){}}));const x=Zt({stdout:E.stdout,stderr:E.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});E.on("error",(async e=>{if((0,Ne.fK)(e,a)){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await C(),i.throw(e)}));let P=null,I=null,R=null,A=!1;const $=async e=>{if(A)return;if(A=!0,R&&(clearTimeout(R),R=null),(0,Ht.HF)(o.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await C(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,Ne.wz)({exitCode:P,stdoutBytes:x.stdoutBytes,stdoutPrefix:x.stdoutPrefix,cwd:a})&&""===k;if(t&&x.dropHeldStdout(),await x.flush(),p&&ir(P,k)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await C(),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,Ne.Vn)(a))}if(!r?.signal?.aborted){await _();const e=`${fr}\n`,t=`${mr}\n`;if(k.startsWith(e)&&k.endsWith(t)){let t=k.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=dr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(S.captureDenies)try{const e=await Ut(E);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:P,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await C()};E.on("exit",((e,t)=>{P=e,I=t;const n=r?.closeTimeout??5e3;n>0&&(R=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),$(!1)}),n))})),E.on("close",(async()=>{await $(!0)}));const M=E.stdio[3],F=E.stdio[4],N=M instanceof Wt.Writable?M:null,L=F instanceof Wt.Readable?F:null;p&&cr(E,t),d||(lr(N,this.state),ur(L,(e=>{k+=e}))),yield*i}catch(e){n.error=e,n.hasError=!0}finally{gr(n)}}}async function Sr(e){const t={...process.env,...er,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=wr(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const s=rr(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal),i=nr(s.stdout);s.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=pr(hr(i(),r),fr,mr)??`${process.cwd()}\n`,{cwd:c,rest:l}=dr(a),u="win32"===process.platform,d="win32"===process.platform?process.cwd():c;return new br(d,l,e?.userTerminalHint,u)}var kr=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 _r{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new _r((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={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})}(n,(0,Ht.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{kr(n)}}}const Cr="\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",Er=e=>e.map((e=>`'${e}'`)).join(", "),xr=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $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 $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\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 if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.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; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\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 'either' }\n if ($__cursorFull) {\n # A full window 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 }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\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 # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\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 -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\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 # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\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}\n'@\n if (-not $__cursorHasEncodingDefault) {\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 Get-Content -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 $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\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:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # 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 @(${Er([".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 @(${Er([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${Er([".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 @(${Er([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${Er([".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 }\n }\n} catch { }\n`,Pr=String.raw` ++const s2codeRetryGuard=require("../s2code-retry.cjs"); ++exports.id=305,exports.ids=[305],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>$N});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../context/dist/otel.js"),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});class u{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,c.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{l(e)}}}function d(e){return e instanceof Error?e.message:String(e)}function h(e){return"Failed to read skill file: "+d(e)}function p(e){return"Invalid skill frontmatter: "+d(e)}function f(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const m=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function g(e){return e.toLocaleString("en-US")}var w=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const y=102400;function v(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function b({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>y?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=y;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 S(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function k(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$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(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=e.slice(r+1).trim(),c=S(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=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=S(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 _(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 C(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const E=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];var x=r("../context/dist/logger.js"),P=r("../metrics/dist/index.js"),I=r("../proto/dist/generated/agent/v1/exec_pb.js"),R=r("../utils/dist/writable-iterable.js");const T=/https?:\/\/\S+/gi,A=/[)"'<>,.;:\]}]$/;function $(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&A.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(T,$),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const O=(0,x.h)("SimpleControlledExecManager"),F=(0,P.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),N=(0,P.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),j=(0,P.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),L={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 U extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function B(e){return e instanceof U?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class W{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}),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 H{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 I.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class q{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t}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,R.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new I.$Y({message:{case:"heartbeat",value:new I.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new I.$Y({message:{case:"streamClose",value:new I.D9({id:t.id})}})),N.increment(r,1,{exec_case:o})}catch(e){if(e instanceof R.W2)return;j.increment(r,1,{exec_case:o}),await a.write(new I.$Y({message:{case:"throw",value:new I.Fu({id:t.id,error:e instanceof Error?D(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:B(e)})}}))}finally{const e=performance.now()-u;F.histogram(r,e,{exec_case:o}),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:L[s])??`No handler found for server message of type ${s}`;return O.error(e,i,{messageCase:s}),j.increment(e,1,{exec_case:o}),async function*(){yield new I.$Y({message:{case:"throw",value:new I.Fu({id:t.id,error:i})}}),yield new I.$Y({message:{case:"streamClose",value:new I.D9({id:t.id})}})}()}static fromResources(e,t){const r=new q(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}async function z(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}}var G=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},V=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 K=(0,x.h)("ExecutorResource"),J=(0,P.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class Z{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=G(n,(0,c.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,c.mJ)(s),a=i?new I.Kg(i):void 0,l=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new I.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await z(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)J.increment(s,1,{hook_event_name:t.hookEventName})}};p(d);let f=this.deserializeResult(d);for(;void 0===f;){const e=await z(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),f=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)p(e)}catch(e){K.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),f}catch(e){n.error=e,n.hasError=!0}finally{V(n)}}}class X{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=G(n,(0,c.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,c.mJ)(o),i=s?new I.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new I.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of a){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{V(n)}}}function Q(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function Y(e,t,r){return{name:e,symbol:Q(e),remoteImplementation:t,registerControlledImplementation:r}}class ee{constructor(e,t){this.resource=e,this.value=t}}function te(e,t){return[e,t]}function re(e,t){return t}class ne{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new ee(e,t))}get(e){return re(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class oe{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?re(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 se(e){return function(t,r){return new I.Ye({id:t,message:{case:e,value:r}})}}function ie(e){return t=>{if(t.message.case===e)return t.message.value}}function ae(e){return function(t,r){const n={case:e,value:r};return new I.yT({id:t,message:n})}}function ce(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const le=Y("agent-store-conflict-executor",(e=>new Z(e,se("agentStoreConflictArgs"),ie("agentStoreConflictResult"))),((e,t)=>{t.register(new W(e,ce("agentStoreConflictArgs"),ae("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class ue{async execute(e,t){return"ack"===t.op?{kind:"acked",count:0}:"release"===t.op?{kind:"released",count:0}:"noteDeferredEagerWrittenPaths"===t.op?{kind:"noted",count:0}:{kind:"not-applicable"}}}Y("agent-store-conflict-notice-executor",(e=>new ue),((e,t)=>{}));const de=Y("background-shell-executor",(e=>new Z(e,se("backgroundShellSpawnArgs"),ie("backgroundShellSpawnResult"))),((e,t)=>{t.register(new W(e,ce("backgroundShellSpawnArgs"),ae("backgroundShellSpawnResult")))})),he=Y("write-background-shell-input-executor",(e=>new Z(e,se("writeShellStdinArgs"),ie("writeShellStdinResult"))),((e,t)=>{t.register(new W(e,ce("writeShellStdinArgs"),ae("writeShellStdinResult")))}));function pe(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}const fe="local";function me(e,t){return`${e}:task_progress:${t}`}const ge=Y("canvas-diagnostics-executor",(e=>new Z(e,se("canvasDiagnosticsArgs"),ie("canvasDiagnosticsResult"))),((e,t)=>{t.register(new W(e,ce("canvasDiagnosticsArgs"),ae("canvasDiagnosticsResult")))}));Error;const we=Y("computer-use-executor",(e=>new Z(e,se("computerUseArgs"),ie("computerUseResult"))),((e,t)=>{t.register(new W(e,ce("computerUseArgs"),ae("computerUseResult")))})),ye=(Y("conversation-search-executor",(e=>new Z(e,se("conversationSearchArgs"),ie("conversationSearchResult"))),((e,t)=>{t.register(new W(e,ce("conversationSearchArgs"),ae("conversationSearchResult")))})),Y("delete-executor",(e=>new Z(e,se("deleteArgs"),ie("deleteResult"))),((e,t)=>{t.register(new W(e,ce("deleteArgs"),ae("deleteResult")))}))),ve=Y("diagnostics-executor",(e=>new Z(e,se("diagnosticsArgs"),ie("diagnosticsResult"))),((e,t)=>{t.register(new W(e,ce("diagnosticsArgs"),ae("diagnosticsResult")))}));var be=r("../context/dist/core.js");(0,be.cF)(Symbol("execConversationId"),void 0),(0,be.cF)(Symbol("execRequestId"),void 0),(0,be.cF)(Symbol("execBrowserOperationSource"),void 0);const Se=Y("fetch-executor",(e=>new Z(e,se("fetchArgs"),ie("fetchResult"))),((e,t)=>{t.register(new W(e,ce("fetchArgs"),ae("fetchResult")))})),ke=Y("git-diff-executor",(e=>new Z(e,se("gitDiffRequest"),ie("gitDiffResponse"))),((e,t)=>{t.register(new W(e,ce("gitDiffRequest"),ae("gitDiffResponse")))})),_e=Y("grep-executor",(e=>new Z(e,se("grepArgs"),ie("grepResult"))),((e,t)=>{t.register(new W(e,ce("grepArgs"),ae("grepResult")))})),Ce={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"},Ee={PreToolUse:Ce.preToolUse,PermissionRequest:null,PostToolUse:Ce.postToolUse,UserPromptSubmit:Ce.beforeSubmitPrompt,Stop:Ce.stop,SubagentStop:Ce.subagentStop,SessionStart:Ce.sessionStart,SessionEnd:Ce.sessionEnd,PreCompact:Ce.preCompact,Notification:null},xe=Object.fromEntries(Object.entries(Ee).filter((e=>Pe(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Pe(e){return Object.prototype.hasOwnProperty.call(Ee,e)}const Ie={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Re=["Glob"],Te=["Notification","PermissionRequest"],Ae=e=>"string"==typeof e,$e=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Me=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),De=(e,t=[])=>({isValid:e,errors:t});function Oe(e,t,r){void 0===e||Ae(e)||r.push(`${t} must be a string if provided`)}const Fe={warn:()=>{},info:()=>{}};function Ne(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?{type:"prompt",prompt:e.prompt,...r}:null:e.command?{type:"command",command:e.command,...r}:null}function je(e,t,r=Fe){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Fe){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=Ie[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Re.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=Ne(t,o);e&&n.push(e)}return n}function Le(e,t=Fe){const r={};for(const[n,o]of Object.entries(e)){if(!Pe(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Te.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Ee[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=je(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}}function Ue(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}const Be="Agent note: Do not suggest workarounds to the blocked tool.";function We(e){return e.includes(Be)?e:`${e}\n\n${Be}`}function He(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 qe(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)))}const ze=e=>{const t=[];return $e(e)?De(!0):(t.push("Expected an object"),De(!1,t))},Ge=e=>{const t=[],r=ze(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"),De(0===t.length,t)};function Ve(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 Ke=new Set([Ce.sessionStart,Ce.beforeSubmitPrompt,Ce.preToolUse,Ce.postToolUse,Ce.postToolUseFailure]);function Je(e){return"prompt"===e.type}function Ze(e){return"command"===e.type||void 0===e.type}const Xe={[Ce.beforeShellExecution]:Ge,[Ce.beforeMCPExecution]:Ge,[Ce.afterShellExecution]:e=>{const t=ze(e);return t.isValid,t},[Ce.afterMCPExecution]:e=>{const t=ze(e);return t.isValid,t},[Ce.beforeReadFile]:e=>{const t=[],r=ze(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"),De(0===t.length,t)},[Ce.afterFileEdit]:e=>{const t=ze(e);return t.isValid,t},[Ce.beforeTabFileRead]:e=>{const t=[],r=ze(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"),De(0===t.length,t)},[Ce.afterTabFileEdit]:e=>ze(e),[Ce.beforeSubmitPrompt]:e=>{const t=ze(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||Ae(e.additional_context)||r.push("additional_context must be a string if provided"),De(0===r.length,r)},[Ce.stop]:e=>{const t=ze(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"),De(0===r.length,r)},[Ce.afterAgentResponse]:e=>{const t=ze(e);return t.isValid,t},[Ce.afterAgentThought]:e=>{const t=ze(e);return t.isValid,t},[Ce.sessionStart]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if($e(e.env))for(const[t,n]of Object.entries(e.env))Ae(t)||r.push(`env key "${t}" must be a string`),Ae(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||Ae(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||Ae(e.user_message)||r.push("user_message must be a string if provided"),De(0===r.length,r)},[Ce.sessionEnd]:e=>{const t=ze(e);return t.isValid?De(!0,[]):t},[Ce.preCompact]:e=>{const t=ze(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return De(!0,[]);const r=[];if(!Me(e))return r.push("PreCompact response must be an object"),De(!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"),De(0===r.length,r)},[Ce.subagentStart]:e=>{const t=ze(e);if(!t.isValid)return t;if(!Me(e))return De(!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||Ae(n.user_message)||r.push("user_message must be a string if provided"),De(0===r.length,r)},[Ce.subagentStop]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];return Me(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),De(0===r.length,r)},[Ce.preToolUse]:e=>{const t=[],r=ze(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"),Oe(e.additional_context,"additional_context",t),De(0===t.length,t)},[Ce.postToolUse]:e=>{const t=[],r=ze(e);return r.isValid?(Oe(e.additional_context,"additional_context",t),De(0===t.length,t)):r},[Ce.postToolUseFailure]:e=>{const t=ze(e);if(!t.isValid)return t;const r=[];return Oe(e.additional_context,"additional_context",r),De(0===r.length,r)},[Ce.workspaceOpen]:e=>{const t=ze(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")),De(0===r.length,r)}},Qe=(e,t,r)=>{const n=function(e,t,r){let n;n=e===Ce.preToolUse?function(e,t){if(!lt(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(!ct(t))return r;const n=ut(e);if(!dt(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),lt(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Ce.stop?ht(t,r,"Stop"):e===Ce.subagentStop?ht(t,r,"SubagentStop"):t;const o=function(e,t,r,n){if(!Ke.has(e)||!lt(r)||void 0!==r.additional_context)return r;const o=lt(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!ct(r))return;const n=xe[e];if(void 0===n)return;const o=ut(t);return dt(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);return o}(e,t,r),o=(0,Xe[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Ye=[Ce.beforeShellExecution,Ce.beforeMCPExecution,Ce.beforeReadFile,Ce.beforeTabFileRead,Ce.subagentStart,Ce.preToolUse],et=[Ce.workspaceOpen];function tt(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 rt(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function nt(e){return Ye.includes(e)}function ot({step:e,command:t,failClosed:r,kind:n}){const o=nt(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:it(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function st(e,t){return t}function it(e,t){return nt(e)?st(0,{permission:"deny",user_message:t}):e===Ce.beforeSubmitPrompt||e===Ce.sessionStart?st(0,{continue:!1,user_message:t}):e===Ce.stop?st(0,{}):void 0}function at(e){try{return{value:JSON.parse(e)}}catch{return}}function ct(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function lt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ut(e){if(!lt(e))return;const t=e.hookSpecificOutput;return lt(t)?t:void 0}function dt(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function ht(e,t,r){if(!lt(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return{...n,followup_message:n.reason.trim()};if(!ct(t))return n;const o=ut(e),s=dt(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 pt=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function ft(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;e{const t=[];if(!$e(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)"),De(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Ae(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&&(Ae(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)=>{Ae(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(Ae(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),De(0===t.length,t)},kt=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),De(!1,r);for(let n=0;n{const t=[];if(!$e(e))return t.push("Hooks config must be an object"),De(!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"),!$e(e.hooks))return t.push("Config hooks must be an object"),De(!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(Ce),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=kt(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return De(0===t.length,t)};var Ct=r("../proto/dist/generated/agent/v1/hooks_pb.js");(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,be.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,be.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const Et=(0,be.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),xt=(0,be.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function Pt(e){return"inExecute"!==e.get(xt).kind}function It(e,t){const r=e.get(xt);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}const Rt=Y("hook-executor",(e=>new Z(e,se("executeHookArgs"),ie("executeHookResult"))),((e,t)=>{t.register(new W(e,ce("executeHookArgs"),ae("executeHookResult")))})),Tt=new Set(Object.values(Ce));function At(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function $t(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function Mt(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class Dt{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return Tt.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new I.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??"",...Ve(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(Ce.preCompact,t);return new I.S1({response:new I.w5({response:{case:"preCompact",value:new Ct.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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(Ce.subagentStart,t);return new I.S1({response:new I.w5({response:{case:"subagentStart",value:new Ct.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??"",...Ve(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:At(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(Ce.subagentStop,t);return new I.S1({response:new I.w5({response:{case:"subagentStop",value:new Ct.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Ce.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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 I.S1({response:new I.w5({response:{case:"beforeSubmitPrompt",value:new Ct.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Ce.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(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 I.S1({response:new I.w5({response:{case:"afterAgentResponse",value:new Ct.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Ce.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new I.S1({response:new I.w5({response:{case:"afterAgentThought",value:new Ct.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Ce.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Ve(e),status:At(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 I.S1({response:new I.w5({response:{case:"stop",value:new Ct.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(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(Ce.preToolUse,o);return new I.S1({response:new I.w5({response:{case:"preToolUse",value:new Ct.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(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(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(Ce.postToolUse,o);return new I.S1({response:new I.w5({response:{case:"postToolUse",value:new Ct.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!Pt(e))return this.skipToolUseStep();const t=r.request.value,n=Mt(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...Ve(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:$t(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Ce.postToolUseFailure,o);return new I.S1({response:new I.w5({response:{case:"postToolUseFailure",value:new Ct.U1({additionalContext:s?.additional_context})}})})}default:return new I.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new I.S1({response:void 0})}}(0,be.cF)(Symbol("execHookConversationId"),void 0),(0,be.cF)(Symbol("execHookGenerationId"),void 0),(0,be.cF)(Symbol("execHookModel"),void 0);const Ot=(0,be.cF)(Symbol("execHookWorkspaceRoots"),void 0),Ft=Y("ls-executor",(e=>new Z(e,se("lsArgs"),ie("lsResult"))),((e,t)=>{t.register(new W(e,ce("lsArgs"),ae("lsResult")))})),Nt="cursor-ide-browser",jt="cursor-dev-control",Lt="custom-user-tools",Ut=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Nt,jt,Lt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Bt(e){return!Ut.has(e)}const Wt=new Set([jt,Nt]);function Ht(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function qt(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 zt;function Gt(e){return void 0===e||void 0===e.serverIdentifiers}function Vt(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,be.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"}(zt||(zt={}));const Kt=Y("mcp-executor",(e=>new Z(e,se("mcpArgs"),ie("mcpResult"))),((e,t)=>{t.register(new W(e,ce("mcpArgs"),ae("mcpResult")))})),Jt=Y("list-mcp-resources-executor",(e=>new Z(e,se("listMcpResourcesExecArgs"),ie("listMcpResourcesExecResult"))),((e,t)=>{t.register(new W(e,ce("listMcpResourcesExecArgs"),ae("listMcpResourcesExecResult")))})),Zt=Y("read-mcp-resource-executor",(e=>new Z(e,se("readMcpResourceExecArgs"),ie("readMcpResourceExecResult"))),((e,t)=>{t.register(new W(e,ce("readMcpResourceExecArgs"),ae("readMcpResourceExecResult")))})),Xt=Y("mcp-state-executor",(e=>new Z(e,se("mcpStateExecArgs"),ie("mcpStateExecResult"))),((e,t)=>{t.register(new W(e,ce("mcpStateExecArgs"),ae("mcpStateExecResult")))})),Qt=Y("mcp-allowlist-precheck-executor",(e=>new Z(e,se("mcpAllowlistPrecheckArgs"),ie("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("mcpAllowlistPrecheckArgs"),ae("mcpAllowlistPrecheckResult")))}));class Yt extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function er(e){if(e instanceof Yt)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}const tr=8388608;var rr=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),nr=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function or(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class ur{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 lr(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new nr.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const dr=Y("read-executor",(e=>new Z(e,se("readArgs"),ie("readResult"))),((e,t)=>{t.register(new W(e,ce("readArgs"),ae("readResult")))})),hr=Y("redacted-read-executor",(e=>new Z(e,se("redactedReadArgs"),ie("redactedReadResult"))),((e,t)=>{t.register(new W(e,ce("redactedReadArgs"),ae("redactedReadResult")))})),pr="$file:";const fr=(0,P.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),mr=(0,P.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),gr=(0,P.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"]}),wr=(0,P.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function yr(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${pr}${t}": ${r} A string argument of the form "${pr}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class vr extends Error{constructor(e){super(e.message),this.failure=e}}async function br(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=>(fr.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new rr.iz({result:{case:"error",value:new rr.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new vr(yr("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 a=r();if(void 0===a)throw new vr(yr("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,ir.xb)(t,(t=>async function(e,t,r,n,o,s){const i=await t.execute(e,new nr.a2({path:r,toolCallId:n,...s?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,n=s&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===n&&"content"!==t.output.case)throw new vr(yr("not_text",r,"the file is not a text file."));if(s&&(gr.increment(e,1,{source:void 0!==n?"vm_digest":"outdated_executor"}),void 0===n))throw new vr(yr("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."));const a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=n??await lr(a??"");if(t.truncated||l>o)throw new vr(yr("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${o} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return{content:a,bytes:l,sha256:c}}case"fileNotFound":throw new vr(yr("not_found",r,"the file does not exist."));case"permissionDenied":throw new vr(yr("permission_denied",r,"reading it was not permitted."));case"rejected":throw new vr(yr("rejected",r,`${i.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":throw new vr(yr("not_text",r,"the file cannot be read as text."));case"error":throw new vr(yr("read_error",r,i.result.value.error));default:throw new vr(yr("read_error",r,"the read returned no result."))}}(e,a,t,n,s,o)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new vr(yr("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 c}(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof vr?e.failure:yr("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(yr("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(pr))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,ar.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,fr.increment(e,1,{route:r,outcome:"expanded"}),mr.record(e,l,{route:r}),wr.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 Sr=/\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 kr(e,t,r,n){return Sr.test(t)?(fr.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${pr}/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 _r(e){return e.files.map((e=>`"${pr}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class Cr{constructor(e,t){this.inner=e,this.getReadExecutor=t}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 br(e,t,{route:"local",getReadExecutor:this.getReadExecutor});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=kr(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 rr._Z({content:{case:"text",value:new rr.zN({text:_r(r)})}})):"error"===n.result.case&&(n.result.value.error=kr(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const Er=Y("mini-swe-agent-bash-executor",(e=>new Z(e,se("miniSweAgentBashArgs"),ie("miniSweAgentBashResult"))),((e,t)=>{t.register(new W(e,ce("miniSweAgentBashArgs"),ae("miniSweAgentBashResult")))}));var xr=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Pr=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),Ir=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Rr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Tr=Y("shell-executor",(e=>new Z(e,se("shellArgs"),ie("shellResult"))),((e,t)=>{t.register(new W(e,ce("shellArgs"),ae("shellResult")))})),Ar=Y("shell-stream-executor",(e=>new X(e,se("shellStreamArgs"),ie("shellStream"))),((e,t)=>{t.register(new H(e,ce("shellStreamArgs"),ae("shellStream")))})),$r=((0,be.cF)(Symbol("optionalPendingPodWrite"),!1),Y("write-executor",(e=>new Z(e,se("writeArgs"),ie("writeResult"))),((e,t)=>{t.register(new W(e,ce("writeArgs"),ae("writeResult")))})));function Mr(e,t){return new Ir.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function Dr(e){return{execute:async(t,r)=>new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r.path,error:e,isReadonly:!0})}})}}function Or(e){return{execute:async(t,r)=>new Pr.Pi({result:{case:"permissionDenied",value:new Pr.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function Fr(e){return{execute:async(t,r)=>new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}const Nr=Y("record-screen-executor",(e=>new Z(e,se("recordScreenArgs"),ie("recordScreenResult"))),((e,t)=>{t.register(new W(e,ce("recordScreenArgs"),ae("recordScreenResult")))})),jr=Y("request-context-executor",(e=>new Z(e,se("requestContextArgs"),ie("requestContextResult"))),((e,t)=>{t.register(new W(e,ce("requestContextArgs"),ae("requestContextResult")))}));var Lr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const Ur=Y("shell-allowlist-precheck-executor",(e=>new Z(e,se("shellAllowlistPrecheckArgs"),ie("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("shellAllowlistPrecheckArgs"),ae("shellAllowlistPrecheckResult")))})),Br=Y("force-background-shell-executor",(e=>new Z(e,se("forceBackgroundShellArgs"),ie("forceBackgroundShellResult"))),((e,t)=>{t.register(new W(e,ce("forceBackgroundShellArgs"),ae("forceBackgroundShellResult")))}));function Wr(e,t){e.hookApprovalRequirement=void 0!==t?new Ir.In(t):void 0}function Hr(e){return e.hookApprovalRequirement}function qr(e){return e?.kind===Ir.b.FORCE_PROMPT}function zr(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&qr(e.hookApprovalRequirement))}Y("smart-mode-classifier-executor",(e=>new Z(e,se("smartModeClassifierArgs"),ie("smartModeClassifierResult"))),((e,t)=>{t.register(new W(e,ce("smartModeClassifierArgs"),ae("smartModeClassifierResult")))}));var Gr=r("../proto/dist/generated/agent/v1/agent_pb.js"),Vr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Kr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),Jr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Zr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Xr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Qr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Yr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class en 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 tn=e=>new Gr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Yr.lI({result:{case:"approved",value:new Yr.XJ}})}}),rn=(e,t)=>new Gr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Yr.lI({result:{case:"rejected",value:new Yr.yc({reason:t??""})}})}}),nn=e=>new Gr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Qr.fS({result:{case:"approved",value:new Qr.Hs}})}}),on=(e,t)=>new Gr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Qr.fS({result:{case:"rejected",value:new Qr.m$({reason:t??""})}})}}),sn=(e,t)=>new Gr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Gr.zT({result:t})}}),an=e=>new Gr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Xr.w$({result:{case:"approved",value:new Xr.q5}})}}),cn=(e,t)=>new Gr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Xr.w$({result:{case:"rejected",value:new Xr.rA({reason:t??""})}})}}),ln=(e,t)=>new Gr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Kr.gz({result:t})}}),un=(e,t)=>new Gr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),dn=(e,t)=>new Gr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),hn=(e,t)=>new Gr.Y5({id:e,result:{case:"prManagementResult",value:t}}),pn=(e,t)=>new Gr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Zr.h({result:{case:"rejected",value:new Zr.OI({reason:t??"Authentication was rejected"})}})}}),fn=(e,t)=>new Gr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new Vr.qG({result:{case:"rejected",value:new Vr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),mn=(e,t)=>new Gr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Jr.vW({result:{case:"approved",value:new Jr.l3({description:t??""})}})}}),gn=(e,t)=>new Gr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Jr.vW({result:{case:"rejected",value:new Jr.Uq({reason:t??""})}})}});var wn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),yn=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,be.cF)(Symbol("pendingSubagentReplay"),void 0);class vn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const bn=Y("subagent-executor",(e=>new Z(e,se("subagentArgs"),ie("subagentResult"))),((e,t)=>{t.register(new W(e,ce("subagentArgs"),ae("subagentResult")))})),Sn=Y("subagent-await-executor",(e=>new Z(e,se("subagentAwaitArgs"),ie("subagentAwaitResult"))),((e,t)=>{t.register(new W(e,ce("subagentAwaitArgs"),ae("subagentAwaitResult")))})),kn=Y("force-background-subagent-executor",(e=>new Z(e,se("forceBackgroundSubagentArgs"),ie("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new W(e,ce("forceBackgroundSubagentArgs"),ae("forceBackgroundSubagentResult")))}));class _n{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 Cn(e){return"string"==typeof e&&e.trim().length>0}const En=Y("web-fetch-allowlist-precheck-executor",(e=>new Z(e,se("webFetchAllowlistPrecheckArgs"),ie("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new W(e,ce("webFetchAllowlistPrecheckArgs"),ae("webFetchAllowlistPrecheckResult")))})),xn=e=>e.replace(/[\r\n]/g,"");function Pn(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":xn(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":xn(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":xn(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const In="x-inference-authentication-jwt";function Rn(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[In]:t}}const Tn={textDelta:(e,t)=>new Gr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new Gr.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new Gr.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new Gr.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new Gr.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new Gr.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new Gr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new Gr.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new Gr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new Gr.tr3({thinkingDurationMs:e})}}),thinkingNote:e=>new Gr.Uq({message:{case:"thinkingNote",value:new Gr.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:Tn.toolCallDelta(e,new Gr.V1v({delta:{case:"taskToolCallDelta",value:new Gr.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new Gr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new Gr.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new Gr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new Gr.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Gr.Uq({message:{case:"tokenDelta",value:new Gr.Fyz({tokens:e})}}),summary:e=>new Gr.Uq({message:{case:"summary",value:new Gr.ECk({summary:e})}}),summaryStarted:()=>new Gr.Uq({message:{case:"summaryStarted",value:new Gr.lWT}}),heartbeat:()=>new Gr.Uq({message:{case:"heartbeat",value:new Gr.ih1}}),summaryCompleted:(e,t,r)=>new Gr.Uq({message:{case:"summaryCompleted",value:new Gr.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new Gr.Uq({message:{case:"shellOutputDelta",value:new Gr.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new Gr.Uq({message:{case:"modelCallCompleted",value:new Gr.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 Gr.Uq({message:{case:"turnEnded",value:new Gr.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 Gr.QVp({rawCostCents:r,chargedCents:r,source:Gr.nnk.CATALOG})}:{}})}})},stepStarted:e=>new Gr.Uq({message:{case:"stepStarted",value:new Gr.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new Gr.Uq({message:{case:"toolRequestsListed",value:new Gr.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new Gr.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new Gr.Uq({message:{case:"stepCompleted",value:new Gr.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new Gr.Uq({message:{case:"activeBranchChange",value:new Gr.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new Gr.Uq({message:{case:"feedbackRequest",value:new Gr.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class An{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 $n=r("../agent-kv/dist/index.js");function Mn(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 Dn=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),On=r("../utils/dist/fresh-uuid.js"),Fn=r("@connectrpc/connect"),Nn=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),jn=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Ln=r("zod/v4");const Un="relayedAttemptFailure",Bn=Ln.object({transport:Ln.boolean(),stallAborted:Ln.boolean(),errorName:Ln.string(),connectCode:Ln.number().optional(),connectCodeName:Ln.string().optional(),connectCause:Ln.object({code:Ln.union([Ln.string(),Ln.number()]).optional(),name:Ln.string().optional()}).optional(),transportFailureKind:Ln.string().optional(),loop:Ln.string().optional(),transportMode:Ln.string().optional()});function Wn(e){const t=e?.details?.additionalInfo[Un];if(void 0!==t)try{const e=Bn.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class Hn 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 qn extends Hn{get kind(){return"RetriableError"}}class zn extends Hn{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Gn extends Hn{get kind(){return"NonRetriableError"}}class Vn extends Gn{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 Kn extends Hn{get kind(){return"CancelledError"}}const Jn=new Set([jn.yM.NOT_LOGGED_IN,jn.yM.AGENT_REQUIRES_LOGIN,jn.yM.AUTH_TOKEN_NOT_FOUND,jn.yM.AUTH_TOKEN_EXPIRED,jn.yM.INVALID_AUTH_ID,jn.yM.UNAUTHORIZED,jn.yM.GITHUB_NO_USER_CREDENTIALS,jn.yM.GITHUB_USER_NO_ACCESS]),Zn=new Set([jn.yM.FREE_USER_USAGE_LIMIT,jn.yM.FREE_USER_RATE_LIMIT_EXCEEDED,jn.yM.PRO_USER_ONLY,jn.yM.PRO_USER_USAGE_LIMIT,jn.yM.PRO_USER_RATE_LIMIT_EXCEEDED,jn.yM.RATE_LIMITED,jn.yM.RATE_LIMITED_CHANGEABLE,jn.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xn=new Set([jn.yM.USAGE_PRICING_REQUIRED,jn.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qn=new Set([jn.yM.BAD_API_KEY,jn.yM.BAD_USER_API_KEY,jn.yM.OUTDATED_CLIENT]),Yn=new Set([jn.yM.USER_ABORTED_REQUEST,jn.yM.DEBOUNCED]),eo=new Set([jn.yM.CUSTOM_MESSAGE]),to=new Map([[Fn.Code.PermissionDenied,"Permission Denied"]]),ro=["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"],no=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),oo=new RegExp(`\\b(${[...no].join("|")})\\b`),so=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],io="x-cursor-inference-request-error-type",ao="AgentWebSocketDeliveryAmbiguousError";function co(e,t={}){const{requestId:r}=t;if(e instanceof Hn)return e;if(lo(e))return function(e,t){const r=ho(e),n=r.code,o=po(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Un])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Un],t.details.equals(new jn.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:fo(r,io)??fo(e,io),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===Wn(o)?.transport?{isTransport:!0}:{}};if(n===Fn.Code.Canceled||n===Fn.Code.Aborted)return So(e)?new qn(e.message,a):new Kn(e.message,a);if(void 0!==s?.error){const t=s.error;if(Yn.has(t))return new Kn(yo(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new zn(yo(e,s),r,a);if(void 0!==Ro(s))return new qn(yo(e,s),a);if(Jn.has(t))return new zn(yo(e,s),"login",a);if(Zn.has(t))return new zn(yo(e,s),"upgrade",a);if(Xn.has(t))return new zn(yo(e,s),"payment",a);if(Qn.has(t))return new zn(yo(e,s),"config",a);if(eo.has(t)&&!0!==s.details?.isRetryable)return new Gn(yo(e,s),a);if(!1===s.details?.isRetryable)return new Gn(yo(e,s),a)}if(n===Fn.Code.Unauthenticated)return new zn(e.message,"login",{...a,displayInfo:uo(i,"Sign in required",r)});const c=to.get(n);return void 0===c||!0===s?.details?.isRetryable||So(e)?new qn(e.message,a):new Gn(yo(e,s),{...a,displayInfo:uo(i,c,r)})}(e,r);const n=(0,$n.y_)(e);if(void 0!==n)return new Gn(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===vo)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Gn(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 Gn(bo,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:bo,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Kn(e.message,{cause:e,requestId:r});if(e.name===ao)return new qn(e.message,{cause:e,requestId:r,isTransport:!0});if(So(e))return new qn(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qn(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lo(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 uo(e,t,r){return{...e,title:e.title||t,detail:e.detail||wo(r),isRetryable:e.isRetryable??!1}}function ho(e){let t=e;for(let e=0;e<10&&t.code===Fn.Code.Unknown;e++){const e=t.cause;if(!lo(e))break;t=e}return t}function po(e){let t=e;for(let e=0;e<10&&lo(t);e++){try{const e=t.findDetails?.(jn.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function fo(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 mo(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lo(t))return t;t="cause"in t?t.cause:void 0}}function go(e){const t=mo(e);return void 0===t?void 0:ho(t)}function wo(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function yo(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 vo="SummaryPlaceholderRejectedError",bo="Out of disk space. Free some space and try again.";function So(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(ro.some((t=>e.includes(t)))||oo.test(e))return!0;const n=r.code;if("string"==typeof n&&(ro.some((e=>n.includes(e)))||no.has(n)))return!0;r=r.cause}return!1}function ko(e){return ro.some((t=>e.includes(t)))||oo.test(e)}function _o(e){return e instanceof Hn&&e.cause instanceof Error?So(e.cause):e instanceof Error?So(e):"string"==typeof e&&ko(e)}function Co(e){return void 0!==e&&e>0}function Eo(e){return e+1}function xo(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Po(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Co(n)?xo(new qn("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Eo(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):xo(new qn("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}function Io(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(lo(t)&&(t.code===Fn.Code.Canceled||t.code===Fn.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Ro(e){const t=e?.details?.additionalInfo;if(e?.error!==jn.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 To=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},Ao=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 $o extends Error{constructor(e){super(e),this.name="LostConnection"}}class Mo{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{To(t,(0,c.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,ar.isMessage)(t,I.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const n=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,c.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,c.fU)(n)}else n=e;To(r,o?new c.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{Ao(r)}})();r.push(n)}await Promise.all(r)}catch(e){if(e instanceof Fn.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new $o(e.message);if(e instanceof Fn.ConnectError&&e.code===Fn.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 $o(e.message)}else{if(e instanceof R.W2)throw new $o(e.message);if(e instanceof Fn.ConnectError&&e.code===Fn.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new $o(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ao(t)}}}var Do=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Oo=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Fo=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),No=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class jo extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}jo.telemetryName="InteractionListenerStreamClosedError";var Lo=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 Uo=(0,x.h)("ClientInteractionController"),Bo=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Wo{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,c.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=>{Uo.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{Lo(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Bo.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 rn(e.id,t);case"webFetchRequestQuery":return on(e.id,t);case"askQuestionInteractionQuery":return sn(e.id,new Do.tz({result:{case:"rejected",value:new Do.ox({reason:t})}}));case"switchModeRequestQuery":return cn(e.id,t);case"createPlanRequestQuery":return ln(e.id,new Kr.bK({result:{case:"error",value:new Kr.iY({error:t})}}));case"setupVmEnvironmentArgs":return un(e.id,new No.r$({result:{case:"success",value:new No.JH({})}}));case"replaceEnvArgs":return dn(e.id,new Fo.dV({result:{case:"failure",value:new Fo.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return hn(e.id,new Oo.HL({result:{case:"error",value:new Oo.K$({error:t})}}));case"mcpAuthRequestQuery":return pn(e.id,t);case"connectScmRequestQuery":return fn(e.id,t);case"generateImageRequestQuery":return gn(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 Gr.Y5))throw r;return Uo.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=>{Uo.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ho(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Kn("User aborted request");throw new Gn("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Gn("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Gn("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new Gr.Ibo({bearerToken:r.bearerToken})}const qo=15728640,zo=(0,P.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Go=(0,P.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Vo=(0,P.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ko(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Jo{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,$n.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,$n.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,$n.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,$n.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,$n.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,ir.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 Zo({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ko(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(jr),o=await n.execute(e,new Lr._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),qo),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 Lr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Lr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Lr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Lr.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,$n.Bk)(i),(0,$n.Bk)(a),(0,$n.Bk)(c),(0,$n.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Lr.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,zo.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,zo.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 zo.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Go.histogram(e,m,{mode:o}),Vo.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 Xo(e){return Object.keys(e.fileContents).length>0}function Qo(e,t){return Object.assign(new(e.getType()),e,t)}function Yo(e){return Qo(e,{fileContents:{}})}function es(e){for(const[t]of e.entries())if(t.symbol===jr.symbol)return e.get(jr)}class ts{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function rs(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!==w.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=_(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)=>E.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(_);if(!i.some((e=>C(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&&!!(v(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>C(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 Lr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ns(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function os(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ns(r)&&ns(n)&&ns(o)&&ns(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,...ns(i)?{dynamicBytes:i}:{}}}const ss=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],is=/\bHTTP (\d{3})\b/;function as(e){const t=e.message;return"string"==typeof t?t:""}function cs(e){return e instanceof Error&&("AbortError"===e.name||e.name===ao)}const ls={serverCap:3,transportCap:10},us={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 ds(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function hs(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 Hn?e:co(e,{requestId:n});const c=a instanceof Kn&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Yn.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Kn||a instanceof qn),u="owner"===r.abortOrigin&&a instanceof qn&&Io(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(as),o=e=>n.some((t=>t.includes(e))),s=function(e){return go(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===Fn.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===Fn.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>is.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===Fn.Code.Unknown&&"464"===a?"http_464":i&&s===Fn.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===Fn.Code.DeadlineExceeded&&function(e){const t=mo(e);return void 0===t?void 0:po(t)?.error}(e)===jn.yM.TIMEOUT?"idle_deadline":i&&s===Fn.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":_o(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(cs)?"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(Po(f()),{countAsTransportError:!0});const e=p((()=>Po(f())),(()=>Po({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Kn&&!c&&Io(a)&&(a=new qn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Kn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof zn||a instanceof Gn)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!so.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):ds(d);if(a instanceof Kn||a instanceof zn||a instanceof Gn)return h(a);const m=function(e){return Ro(e.displayInfo?.errorDetails)}(a);if(a instanceof qn&&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}}return a instanceof qn&&(!0===a.isTransport||function(e,t){const r=us[e];return"by_signature"===r?_o(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Io(a))?p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Co(n)?new qn("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${Eo(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}}):new qn("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:"The connection was interrupted. Please check your network connection and try again.",isRetryable:!0,connectCode:o}})}(f())),(()=>a),{immediateFirstRetry:!0}):s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qn(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Eo(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):ds(d):h(a)}var ps=r("../proto/dist/generated/agent/v1/mcp_pb.js");const fs=(0,x.h)("@anysphere/agent-client:stall-detector"),ms=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,gs={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},ws=(0,P.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),ys=(0,P.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),vs=(0,P.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),bs=(0,P.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class Ss{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 ks{constructor(e,t,r){this.lastActivityTime=Date.now(),this.lastMeaningfulActivityTime=Date.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.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.logPrefix=gs[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),bs.increment(this.ctx,1,{loop:this.loop}),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}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=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.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=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=Date.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()}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{if(this.paused)return void(this.timer=setTimeout(e,this.thresholdMs));const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{if(this.paused)return void(this.advisoryTimer=setTimeout(t,e));const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{if(this.paused)return void(this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs));const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Ms),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName),this.abortedAt&&(r.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(r.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(r.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const n=[];let o;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:s}=this.activityHistory[e];o!==t&&(o?n.push(`[${t}]`):n.push(`[${t}] (MOST RECENT)`),o=t),n.push(`${r}${s?` (x${s})`:""}`)}return r.activities=n.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=Date.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=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Ms);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(fs.warn(this.ctx,a,i),ws.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",loop:this.loop}),this.hasEverStalled||(this.hasEverStalled=!0,vs.increment(this.ctx,1,{loop:this.loop})),this.onStallCallback){const t=Date.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:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs: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?.()}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});fs.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=Date.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),ys.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",loop:this.loop})}[Symbol.dispose](){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=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const _s=(0,be.cF)(Symbol("agentTransportTimingRecorder"),void 0),Cs=(0,x.h)("@anysphere/agent-client:turn-runner"),Es=1e3,xs=6e4;async function Ps(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Kn("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 Kn("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Is(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 Rs(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Ts(e){e=s2codeRetryGuard.guard(e);const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let c=Es;const l=async(r,o,s,i,a)=>{if(s||(c=Es),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&&Cs.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Ps(n,o)}const l=s?function(e,t){const r=Math.min(3e5,3*e);return t??Es+(r-Es)*Math.random()}(c,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:Es,o=r??Math.min(n*2**e,xs);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,xs),n=Math.min(r+.2*r*Math.random(),xs);return Math.max(e,n)}(l,i.retryAfterMs);u!==l&&e.logging&&Cs.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:l,selectedDelayMs:u,endlessRetries:s}),s&&(c=l,e.logging&&Cs.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 Ps(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let u,d,h,p,f,m=e.state,g=e.action,w=0,y=o,v=0,b=0,S=!1,k=0;const _=()=>{S&&(n.onConnectionStateChange?.({state:"connected"}),S=!1)},C=e=>()=>{e===w&&(f=!0,_())},E=e=>({handleCheckpoint:async(t,n,o)=>{e===w&&(f=!0),await r.handleCheckpoint(t,n,o),e===w&&(u=n,d=o?.resumeEligibility??"eligible",_())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,y);if(u=void 0,d=void 0,f=!1,s.beginAttempt?.({attempt:w,originalRequestId:a}),w>0?(y=(0,On.C)(),await(n.onRetryStarting?.(w,{actionCase:g.action.case,conversationState:m,isResume:"resumeAction"===g.action.case,attemptRequestId:y})),e.logging&&Cs.info(t,`[${e.logging.tag}] Retrying attempt ${w}`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}),"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&Cs.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))):(e.logging&&Cs.info(t,`[${e.logging.tag}] Initial request`,{attempt:w,actionCase:g.action.case,requestId:y}),!0===e.notifyInitialResume&&"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&Cs.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,y);try{return await s.runAttempt({state:m,action:g,checkpointHandler:E(w),attempt:w,attemptRequestId:y,notifyConnected:_,notifyApplicationProgress:C(w)}),_(),void(e.logging&&Cs.info(t,`[${e.logging.tag}] Request successful`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,y);const o=!0===n.endlessRetries?.(),_=e.nowMs?.()??Date.now();f&&(h=void 0,p=void 0);const C=void 0===h?void 0:_-h,E=void 0===p?void 0:_-p;let I=s.classify(r,{attempt:w,attemptRequestId:y,originalRequestId:a,serverErrorRetries:v,transportErrorRetries:b,stallRetryElapsedMs:C,rateLimitRetryElapsedMs:E,endlessRetries:o});if("retry"===I.action){const n="resumeAction"===g.action.case||!0===e.noProgressGuardCountsReplays&&w>0;void 0!==u?k=0:n&&f&&(k++,k>=2&&(e.logging&&Cs.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:k,attempt:w,requestId:y,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),I={action:"throw",error:new qn("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:y,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:I.transportFailureKind}))}const R={...void 0===I.transportFailureKind?{}:{transportFailureKind:I.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},T=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===I.action?`RETRY (countAsServerError=${I.countAsServerError}, countAsTransportError=${I.countAsTransportError})`:`THROW ${I.error.kind}`;Cs.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${y} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===I.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:v,transportErrorRetries:b,attempt:w,requestId:y,originalRequestId:a,...R,...T})}if("throw"===I.action){if(0===w){const r={attempt:0,actionCase:g.action.case,error:I.error,requestId:y,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Cs.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:y,originalRequestId:a})}}throw e.logging&&Cs.warn(t,`[${e.logging.tag}] Error not retryable`,{...R,...T,attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a,errorName:I.error.name,...!0===e.logging.includeErrorObjects?{error:I.error}:{},serverErrorRetries:v,transportErrorRetries:b}),I.error}const A=w+1;if("ineligible_terminal_turn"===d)return void(e.logging&&Cs.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!==I.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:A,trigger:{...R,...s.reconnectTrigger?.(r,I,{originalRequestId:a,failedAttemptRequestId:y,nextAttempt:A})??{originatingRequestId:a,attemptRequestId:y}}}),S=!0),I.countAsServerError&&v++,I.countAsTransportError&&b++,!0===I.stall?h??=_:h=void 0,!0===I.rateLimit?p??=_:p=void 0,w=A,void 0!==u&&(P=u,Is((x=m).turns,P.turns)&&Is(x.rootPromptMessagesJson,P.rootPromptMessagesJson)||(c=Es),m=u,g=new Gr.QFf({action:{case:"resumeAction",value:new Gr.qKo}})),s.onRetryCommitted?.(),!0===I.immediate||!0===I.noBackoff&&void 0===I.retryAfterMs||await l(w,t.signal,o,I,r)}}var x,P}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var As=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},$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 Ms=(0,be.cF)(Symbol("agentStreamMetadata"),void 0),Ds=(0,x.h)("@anysphere/agent-client:abort"),Os=(0,x.h)("@anysphere/agent-client:retry"),Fs=(0,x.h)("@anysphere/agent-client:request-context-blob");async function Ns({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ko(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Xo(r)&&(t.requestContext=Yo(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Xo(o)&&(e.requestContextParts=Qo(n,{dynamicContext:Yo(o)}))}(t);try{const s=await Zo({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??qo,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?os(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?os(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fs.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 js=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 Ls(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 Us(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,Tn.shellOutputDelta({case:"stdout",value:new Ir.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,Tn.shellOutputDelta({case:"stderr",value:new Ir.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,Tn.shellOutputDelta({case:"exit",value:new Ir.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bs(e){return e instanceof Error?e.name:void 0}class Ws{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 Vn(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=es(e);return void 0===t?e:new oe(e,[te(jr,{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&&Xo(r)?new Lr._G({result:{case:"success",value:Qo(t,{requestContext:Yo(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new ts:void 0,y=void 0===w?g:function(e,t){const r=es(e);return void 0===r?e:new oe(e,[te(jr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?rs(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Jo(i),S=d.generationUUID??(0,On.C)(),k=new An,_=(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=mo(e);return void 0===t?void 0:Wn(po(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:Bs(e)},r=go(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=Bs(n);return{...t,underlyingConnectError:{code:r.code,codeName:Fn.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 I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Os.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=As(h,(0,c.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,c.MG)(R.span,(()=>Ts({interaction:_,checkpointError:(cause,requestId,message)=>new Gn(message,{cause,requestId,displayInfo:{title:"Cursor conversation was not saved",detail:message,isRetryable:!1}}),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,...Rs(n)}}},cancellation:{toCancelledError:()=>new Kn("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})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Os.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Kn("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,d,y,b,a,o,u,v,i,S,k,C,c,l,s,I)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=hs(e,function(e,t,r=ls){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)&&ss.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 Hn?e:co(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{$s(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,d,h,p,f,m,g,w,y,v,b,S="agent.request.attempt"){const k={stack:[],error:void 0,hasError:!1};try{const E=e;e=this.options.prepareAttemptContext?.(e,{attempt:v,attemptRequestId:p,originalRequestId:f,runOptions:h})??e;const x=As(k,(0,c.VI)(e.withName(S)),!1);x.span.setAttribute("agent.attempt",v),x.span.setAttribute("agent.request_id",p),x.span.setAttribute("agent.original_request_id",f),e=x.ctx,e=(0,c.Mf)(e,"agent.request_id",p),e=(e=(0,c.Mf)(e,"agent.original_request_id",f)).with(Ms,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const P=new Set(g.sources);let T=void 0!==g.abortReasonName||void 0!==g.abortReasonMessage;const A=(t,r)=>{if(P.has(t))return;P.add(t),g.sources=[...P];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,g.abortReasonName=n.abortReasonName,g.abortReasonMessage=n.abortReasonMessage),Ds.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:p,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",Mn(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",Mn(t))}),{once:!0});const[$,M]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",Mn(e)),M()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",Mn(e)),M()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Kn("User aborted request")}const D=(0,c.VI)(e.withName("createControlledExecManager")),O=q.fromResources(s);D[Symbol.dispose]();const[F,N]=e.withCancel(),j=new Ss,{failThresholdMs:L,advisoryThresholdMs:U}=function(e,t){const r=ms(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=ms(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o{A("stall_detector",{thresholdMs:L,advisoryThresholdMs:U}),N()},onStallCallback:h.onStall,handlerTracker:j}),!1);let W,H;const z=(0,Nn.Jt)(),G=new R.F8(z,(e=>(B.reset("outbound_write",js(e)),e))),V=As(k,(0,c.VI)(e.withName("writeInitialRequest")),!1);let K;const J=function(e){return new ps.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(d),Z=h.requestContextBlobTransportMode??"legacy",X=0===v&&"userMessageAction"===r.action.case&&0===t.turns.length,Q="ref_only"===Z&&X?"dual":Z,[,Y]=await Promise.all([Ns({ctx:e,action:r,resources:s,blobStore:i,options:h,source:"run_request",transportMode:Q,notifyBytes:0===v}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):Ho(h.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:p})]),ee={action:r,headers:h.headers??{}},te=this.options.decorateAttempt?.(ee,h)??ee,re=new Gr.Mpn({conversationState:t,action:te.action,modelDetails:n,requestedModel:h.requestedModel,clientLlmGatewayCredential:Y,mcpTools:J,conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:h.subagentModelOverrides??[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,firstProjectOnboarding:h.firstProjectOnboarding,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,emitModelCallUsage:h.emitModelCallUsage,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,transcriptParentConversationId:h.transcriptParentConversationId,runId:f,nextInteractionQueryId:m.peekNext(),voiceCallNotes:h.voiceCallNotes});if(K=G.write(new Dn.KS({message:{case:"runRequest",value:re}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),V[Symbol.dispose](),new Kn("User aborted request")}const ne={...te.headers,"x-request-id":p,"x-original-request-id":f,...Pn(h),...Rn()};W=(0,c.VI)(e.withName("handshakeEstablishment")),W.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=function(e){return e?.get(_s)}(e)?.startTransportRun(),se=void 0===oe?W.ctx:function(e,t){return e.with(_s,t)}(W.ctx,oe),ie=0===v&&void 0!==h.onTtftBreakdown?b?.networkPhaseStartedAt:void 0;let ae;const ce=void 0===oe&&void 0===ie?z:(_=z,C=()=>{ae=performance.now(),oe?.markFirstRequestSent(ae)},{[Symbol.asyncIterator](){const e=_[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,C()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),le=this.client.run(se,ce,{signal:F.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===H&&(H=performance.now())}}),ue=performance.now();let de;const he=e=>{W&&(W.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==H&&W.span.setAttribute("handshake.preNetworkMs",H-ue),W[Symbol.dispose](),W=void 0),w();const t=performance.now();de=t,h.onFirstMessage?.(t-ue),void 0!==H&&h.onFirstMessageNetwork?.(t-H)},pe=()=>{y(),h.onFirstNonHeartbeatResponse?.(performance.now()-ue,v)},fe=h.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ie||void 0===ae||"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:ie,transportRunCalledAt:ue,firstRequestTakenAt:ae,firstMessageAt:de??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});h.onTtftBreakdown(void 0===r?e:{...e,transit:r},v)}:void 0,{interactionStream:me,execStream:ge,checkpointStream:we,kvStream:ye,done:ve}=function(e,t,r,n,o,s,i,a){const c=(0,Nn.Jt)(),l=(0,Nn.Jt)(),u=(0,Nn.Jt)(),d=(0,Nn.Jt)();let h=!1,p=!1;return{interactionStream:c,execStream:l,checkpointStream:u,kvStream:d,done:async function(){let f,m,g=!1,w=!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.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Os.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(h||(h=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{i?.()}catch(t){Os.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",js(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(g=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await c.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await l.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:o.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===o.message.case&&await d.write(o.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof Hn?e:co(e);return t instanceof qn&&function(e){return!0===e.isTransport||(e.cause instanceof Error?So(e.cause):ko(e.message))}(t)}(f)&&(Os.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)}),r.onStreamEnded(),m=void 0),g||o?.aborted||s?.aborted){if(!g&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${h}`;Os.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(Os.warn(e,t),m=new qn(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(Os.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new qn(t,{cause:f,isTransport:!0})):Os.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Ls(f)})}c.close(),l.close(),u.close(),d.close()}if(void 0!==m)throw m}()}}(e,le,B,he,$.signal,e.signal,pe,fe);let be;const Se={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};V[Symbol.dispose]();const ke=5e3;let _e;const Ce=()=>{_e=setTimeout((()=>{G.write(new Dn.KS({message:{case:"clientHeartbeat",value:new Dn.kA}})).then((()=>B.onClientSentHeartbeat()),(()=>{})),Ce()}),ke)},Ee=()=>{void 0!==_e&&(clearTimeout(_e),_e=void 0)};Ce();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new Ir.a({command:n.shellCommand?.command||"",parsingResult:new Ir.HO,skipApproval:!0}),a=s.get(Ar).execute(e,i,{execId:n.execId}),c=new Wo(me,o,new R.F8(G,(e=>new Dn.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async e=>{await Promise.all([j.track("handleShellStream",Us(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Wo(me,o,new R.F8(G,(e=>new Dn.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==K&&await Promise.race([K,ve.catch((()=>{}))]);const c=new R.F8(G,(e=>{if((0,ar.isMessage)(e,I.yT))return new Dn.KS({message:{case:"execClientMessage",value:e}});if((0,ar.isMessage)(e,I.$Y))return new Dn.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ar.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Mo(ge,c,O),v=new $n.hC(ye,new R.F8(G,(e=>new Dn.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),b=new u(we,Se,e);let S,k;const _={promise:new Promise(((e,t)=>{S=e,k=t})),resolve:S,reject:k};$.canceled?(_.resolve(),me.close()):$.signal.addEventListener("abort",(()=>{_.resolve(),me.close()}),{once:!0}),l.run($).then(_.resolve).catch(_.reject);const C=Promise.allSettled([j.track("streamSplitter",ve.finally((()=>{Ee(),a.close(),c.close()}))),j.track("execHandler",_.promise),t.run(e),j.track("checkpointController",b.run()),j.track("kvHandler",v.run(e)),j.track("conversationActionManager",a.run(e,{write:async t=>{await Ns({ctx:e,action:t,resources:s,blobStore:i,options:h,source:"queued_action"}),await G.write(new Dn.KS({message:{case:"conversationAction",value:t}}))}}))]);let x,P;const T={promise:new Promise(((e,t)=>{x=e,P=t})),resolve:x,reject:P};C.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Kn("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Kn("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?N():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:ve,lingerMs:h.softCancelLingerMs}).then((t=>{Os.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:p}),N()}))};$.canceled?(A(),T.reject(new Kn("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Kn("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],F=M[1],L=M[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new Gn("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===be;if(W){const t={..."rejected"===D.status?{streamSplitter:U(D)}:{},..."rejected"===F.status?{execHandler:U(F)}:{}};Object.keys(t).length>0&&Os.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!W)throw D.reason;if("rejected"===F.status&&!W)throw F.reason;$.canceled||await this.processUnprocessedMessages(E,a,Se,n,o,s,i,d,h,p,f,m,g,B,w,y)}finally{Ee(),W&&(W[Symbol.dispose](),W=void 0)}}catch(e){k.error=e,k.hasError=!0}finally{$s(k)}var _,C}async processUnprocessedMessages(e,t,r,n,o,s,i,a,c,l,u,d,h,p,f,m){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),w=r.getLatestCheckpoint();if(!w||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const v=r.getLatestCheckpoint();try{await this.runInternal(e,w,new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:y})}}),n,o,s,i,t,r,a,c,l,u,d,h,f,m,0,void 0,"agent.request.queuedMessage")}catch(e){throw v===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}new RegExp([String.raw`"type"\s*:\s*"response\.(?:output_text|reasoning_summary_text|reasoning_text|function_call_arguments|refusal)\.(?:delta|done)"`,String.raw`"(?:content|reasoning_content|reasoning|refusal)"\s*:\s*"(?!")`,String.raw`"tool_calls"\s*:\s*\[\s*\{`,String.raw`"type"\s*:\s*"content_block_delta"`].join("|"));var Hs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),qs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const zs=(0,Fn.createContextKey)(void 0,{description:"anysphere.callerContext"});function Gs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function Vs(e){return e instanceof Error?e:new Error(String(e))}function Ks(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(Vs(e)),t?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:Hs.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 Js(...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 Zs(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,l={})=>{const u=(0,c.fR)(i.withName(`rpc.${String(o)}`),{kind:qs.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),d=(0,c.fU)(u);let h;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,c.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}(u)),n){const e=n(u);e&&(o=Js(o,e))}const i=Js(l.headers,o),{signal:f,cleanup:m}=!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)}}}(u.signal,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,Fn.createContextValues)()).set(zs,u),w={...l,headers:i,signal:f,contextValues:g},y=s.call(e,a,w);return Gs(y)?Ks(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?Promise.resolve(y).then((e=>Gs(e)?Ks(e,d,h):(d?.setStatus({code:Hs.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(Vs(e)),d?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:Hs.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(Vs(e)),d?.setStatus({code:Hs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Xs=r("node:crypto"),Qs=r("../utils/dist/workspace-paths.js");function Ys(){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 ei(e){return(0,s.join)(Ys(),(0,Qs.r_)(e))}var ti=r("node:fs/promises"),ri=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),ni=r("node:fs"),oi=r("../shell-exec/dist/api/index.js"),si=r("./src/agent/native/tree-sitter.webpack.cjs"),ii=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const ai=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(ii),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 si)),ci=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),li=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function ui(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=>li.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)ci.has(r.type)&&h(r,t)})(t),ci.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 di(e){return ui(ai(),e)}function hi(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function pi(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function fi(e,t){const r=pi(e,t);return hi(e,r)?r-1:r}function mi(e,t){const r=pi(e,t);return hi(e,r)?r+1:r}function gi(e,t){return t>0?e.length<=t?e:e.slice(0,fi(e,t)):""}function wi(e,t){return t>0?e.length<=t?e:e.slice(mi(e,e.length-Math.trunc(t))):""}let yi,vi;function bi(e,t){yi??=new TextEncoder,vi??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ki.o1)(e);try{return await(0,ti.realpath)(t)}catch{return t}},Ei=1048576,xi=52428800;var Pi=r("../utils/dist/test-resets.js");const Ii="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ri="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Ti=/\$\(|`|<\(|>\(/,Ai=/[;&|]/;let $i,Mi,Di,Oi;function Fi(){if(void 0===$i){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();$i=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return $i}function Ni(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 ji(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Li(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 Ui(){if(void 0===Oi){const e=(process.env[Ii]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Ii} (expected "allow" or "deny"); using "deny".`);const r=ji("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ri]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=ji(Ri)),Oi={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:ji("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Li("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Oi}function Bi(e,t,r={}){const n=[Ni(e),Ni(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 Wi(e,t){const r=function(){const e=Ui();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===Mi&&(Mi=Bi("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Mi);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Ti.test(e))return r;const s=(void 0===Di&&(Di=Bi("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Di);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ai.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ui();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,Pi.J)((function(){$i=void 0,Mi=void 0,Di=void 0,Oi=void 0}));var Hi=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function qi(e){if(!e)return;let t;return"allow"===e.default?t=Hi.h1.ALLOW:"deny"===e.default&&(t=Hi.h1.DENY),new Hi.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Hi.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function zi(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 Hi.h1.ALLOW:t.default="allow";break;case Hi.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,oi.T6)():(0,oi.Po)())}function Gi(e){switch(e){case"system":return Hi.Sz.SYSTEM;case"workspace":return Hi.Sz.WORKSPACE;default:return Hi.Sz.UNSPECIFIED}}function Vi(e){const t=function(e){switch(e){case Hi.Sz.SYSTEM:return"system";case Hi.Sz.WORKSPACE:return"workspace";case Hi.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Ki(e){if(!e)return{type:"insecure_none"};switch(e.type){case Hi.vc.INSECURE_NONE:case Hi.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Hi.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:zi(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,...Vi(e)};case Hi.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:zi(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Vi(e)};default:return{type:"insecure_none"}}}function Ji(e){if(e)return"insecure_none"===e.type?new Hi.Mw({type:Hi.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Hi.Mw({type:Hi.vc.WORKSPACE_READWRITE,networkAccess:(0,oi.$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:qi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Hi.Mw({type:Hi.vc.WORKSPACE_READONLY,networkAccess:(0,oi.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:qi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Hi.Mw({type:Hi.vc.INSECURE_NONE})}function Zi(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function Xi(e){let t="",r=!1;for(const n of e)Zi(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Qi(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const na={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function oa(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=na[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 Xi(t)}function sa({rule:e,command:t}){const r=Xi(e).trim();return 0!==r.length&&(null!==function(e){const t=Xi(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Qi(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=Yi(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Qi(e)&&(0===t.length||Qi(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Xi(t).trim(),oa(t).trim()].some((e=>function(e,t){const r=Yi(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(ta(e,s)&&ta(n,i))return!0}return e.includes("*")?ta(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ia({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=>sa({rule:e,command:t}))))return e}function aa(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 ca({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=ia({matchForms:ra({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:aa(n)}var la=r("../utils/dist/lru-cache.js");const ua=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],da="/Volumes";function ha(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function pa(e,t){if("darwin"!==t.platform)return[];const r=ha(e),n=r.toLowerCase(),o=ha(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...ua.map((e=>`${o}/${e}`)),da].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var fa=r("node:util"),ma=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),ga=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function wa(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const ya="utf8",va="utf8bom",ba="latin1",Sa={"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 ka(e){return Sa[e]||e}function _a(e){return e.startsWith("\ufeff")?e.slice(1):e}function Ca(e){const t=e.toLowerCase();return"latin-1"===t?ba:"utf-8"===t?ya:"utf-8-bom"===t||"utf-8 bom"===t?va:t}function Ea(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 xa=new fa.TextDecoder("utf-8",{fatal:!1}),Pa=new fa.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),Ia="�";function Ra(e){return xa.decode(e)}function Ta(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function Aa(e){let t=0,r=e.indexOf(Ia);for(;-1!==r;)t++,r=e.indexOf(Ia,r+1);return t}function $a(e,t){const r=e[t];let n,o=128,s=191;if(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 Ma(e){return e<128?1:e<2048?2:e<65536?3:4}var Da;!function(e){e.CRLF="CRLF",e.LF="LF"}(Da||(Da={}));const Oa=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Fa=new Set(Oa),Na=new fa.TextDecoder("utf-8",{fatal:!0}),ja=new fa.TextDecoder("latin1"),La=Buffer.from([239,187,191]),Ua={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Ba=8192,Wa="UTF-8",Ha="windows-1252",qa=/[^\u0000-\u007f\ufffd]/u,za=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ga=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Va=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ka=new Map([["windows-1251",za],["ISO-8859-5",za],["KOI8-R",za],["x-mac-cyrillic",za],["IBM866",za],["IBM855",za],["ISO-8859-7",Ga],["windows-1253",Ga],["windows-1255",Va],["ISO-8859-8",Va],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ja=/\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,Za=/[\p{L}\p{M}]+/gu,Xa=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Qa=new RegExp(`[A-Za-z]${Xa}{1,2}(?!${Xa})|^${Xa}{1,2}[A-Za-z]`,"u"),Ya=new Map,ec=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Oa]),tc=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i,rc=new Set([".ps1",".psm1",".psd1"]),nc=/[^\u0000-\u007f]/u;function oc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function sc(e){const t=oc(e);return Fa.has(t)}function ic(e){const t=oc(e);return{encoding:"binary",lineEnding:Da.LF,isBinaryFile:!0,isImageFile:tc.test(t),isVideoFile:Fa.has(t)}}async function ac(e,t){return(await cc(e,t)).text}async function cc(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,ti.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=hc(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=bc(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=_c(n,i),l=_a(a),u=c===ya&&(d=n).length>=La.length&&d[0]===La[0]&&d[1]===La[1]&&d[2]===La[2]?va:c;var d;return Sc(e,r,u),o.lineEnding===Da.CRLF?{text:l.replaceAll("\r\n","\n"),encoding:u}:{text:l,encoding:u}}async function lc(e,t){if("binary"===t.encoding)return void vc(e);let r;try{r=await(0,ti.stat)(e)}catch{return void vc(e)}r.size===t.buffer.byteLength?Sc(e,r,t.encoding):vc(e)}async function uc(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await dc(e)}catch{}const r=oc(e);if(ec.has(r))return ic(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of wc(e)){if(r>=100)break;try{const e=await dc(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:yc()}(t)}catch{return yc()}}(e,r):await dc(e)}catch{const t=oc(e);s=ec.has(t)?ic(e):yc()}const a=()=>i??=async function(e){try{const t=await(0,ti.stat)(e);if(!t.isFile()||t.size>tr)return;return await(0,ti.readFile)(e)}catch{return}}(e),c=bc(e,await async function(e){try{return await(0,ti.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Ca(o):c?r=Ca(c):(r=Ca(s.encoding),r!==ya&&r!==va||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:kc(r).encoding===ba?ba:e}(r,a))),r===ya&&!o&&function(e,t){return"win32"===process.platform&&rc.has(oc(e))&&nc.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,ti.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=va);const i=r===va||r===ya&&!o&&await Cc(e,La),u=Ua[ka(r)];i?l=La:u&&await Cc(e,u)&&(l=u),s={...s,encoding:i?va:r}}const u=wa(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=_a(_c(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=Ea(t),o=Ea(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?_a(t):t,p=s.encoding===va?ya:s.encoding,f=p===ya?await async function(e,t){if(!t.includes(Ia))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(Ia)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Pa.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=Ma(o);continue}const s=$a(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(Ia);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:fc(ma.decode(e.subarray(0,Ba),ka(Ca(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Ba,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:Wa,lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=Ra(e),s=e.length,Ta(o)||1024*Aa(o)<=s&&!qa.test(o)))return{encoding:Wa,lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=ga.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ka.get(a);return void 0!==c&&(a=function(e,t,r){const n=ka(Ca(t));if(!ma.encodingExists(n))return t;const o=ma.decode(e,n);return Ja.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of ma.decode(e,Ha).matchAll(Za))Qa.test(t)&&o++;return o>n}(e,o,r)?Ha:t}(e,a,c)),a!==Ha||function(e,t){const r=ka(Ca(t));return!ma.getDecoder(r).write(e).includes(Ia)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:pc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function pc(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return mc(t,r)}function fc(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return mc(r,t-r)}function mc(e,t){return 0===e&&0===t?Da.LF:e/(e+t)*100>=5?Da.CRLF:Da.LF}async function gc(e){const t=await(0,ti.open)(e,"r");try{const e=Buffer.allocUnsafe(Ba),{bytesRead:r}=await t.read(e,0,Ba,0);return e.subarray(0,r)}finally{await t.close()}}async function*wc(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,ti.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*wc(r)):n.isFile()&&(yield r)}}catch(e){return}}function yc(){return{encoding:ya,lineEnding:"win32"===process.platform?Da.CRLF:Da.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function vc(e){Ya.delete(e)}function bc(e,t){const r=Ya.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ya.delete(e)}function Sc(e,t,r){if(Ya.has(e)&&Ya.delete(e),Ya.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ya.size<=100)return;const n=Ya.keys().next().value;void 0!==n&&Ya.delete(n)}function kc(e){try{return{text:Na.decode(e),encoding:ya}}catch{const t=Ra(e);return Ta(t)?{text:t,encoding:ya}:{text:ja.decode(e),encoding:ba}}}function _c(e,t){const r=Ca(t);if(r===ya||r===va||"ascii"===r){const t=kc(e);return r===va&&t.encoding===ya?{text:t.text,encoding:va}:t}if(r===ba)return{text:ja.decode(e),encoding:ba};try{const t=ka(r);if(ma.encodingExists(t))return{text:ma.decode(e,t),encoding:r}}catch{}return kc(e)}async function Cc(e,t){try{return(await gc(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Ec=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),xc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class Pc{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Pc.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=hc(t);return r.isBinaryFile?Ra(t):_a(_c(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(Ac??=(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,ni.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),Ac),n=(0,s.join)(r,`cursorignore-${$c(e)}-${$c(t)}.txt`);if(await Mc(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,ti.writeFile)(i,t,"utf8"),await(0,ti.rename)(i,n),n}(e,r)}(e,await(0,ti.readFile)(e));return Rc.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function Oc(e){return Promise.all(e.map((e=>async function(e){const t=Tc.get(e);if(void 0!==t)return t;const r=Dc(e).catch((()=>e)).finally((()=>{Tc.delete(e)}));return Tc.set(e,r),r}(e))))}(0,Pi.J)((function(){Rc.clear(),Tc.clear()}));var Fc=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 Nc(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 jc(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 Oc(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,oi.spawnInSandbox)((0,oi.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=Nc(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 Ic.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{Fc(r)}}(),didTimeout:w}}var Lc=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 Uc;function Bc({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 Wc{constructor(e=()=>function(e=process.env){if(void 0!==Uc)return Uc;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}()){this.cache=new Pc({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(Bc(e))}walk(e,t){const r=Bc(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,Nc(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{Lc(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=jc(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 Hc=[{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 qc(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map(Hc.map((e=>[e.gitHost,e.apiHost]))),new Map(Hc.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Hc.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Hc.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Hc.map((e=>[e.apiHost,e.gitHost]))),new Map(Hc.map((e=>[e.apiHost,e.internalHost]))),new Map,function(e){const t=Hc.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t}("prod").gitHost;const zc=new Map;function Gc(e){if(void 0===e)return;if(zc.has(e))return zc.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||!qc(t.hostname))return;const r=function(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}`:""}(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 zc.size>=16384&&zc.clear(),zc.set(e,t),t}function Vc(e){return void 0!==function(e){const t=Gc(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 Kc=new WeakMap;function Jc(e,t,r){const n=performance.now();let o=Kc.get(t);void 0===o&&(o=new Map,Kc.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function Zc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Xc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Yc(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=Qc.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)??Yc(t)??t}}const Qc=new Set(["ftp","file","http","https","ws","wss"]);function Yc(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)}`))}function rl(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function nl(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""}const ol=[".gitignore",".cursorignore"],sl=new Map,il=new Map;function al(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 cl(e){const t=sl.get(e);return void 0!==t?t:al(sl,2048,e,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())}async function ll(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ki.DN)(e);return null===t?null:t}async function ul(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}(0,Pi.J)((function(){sl.clear(),il.clear()}));class dl{constructor(e,t,r){this.disposeRequested=!1,this.ignoreServicePromise=fl.init((0,be.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ignoreServicePromise.then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise.then((e=>{e.dispose()})).catch((()=>{})))}}const hl=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class pl{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=Ec().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class fl{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 la.q({max:2e3}),this.cursorIgnoreCache=new la.q({max:2e3}),this.gitRootCache=new la.q({max:1e4}),this.gitRemoteUrlCache=new la.q({max:200}),this.hasGitDirCache=new la.q({max:1e3}),this.gitParsedIgnoreCache=new pl(1e4),this.cursorParsedIgnoreCache=new pl(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new la.q({max:1e4}),this.unwalkedFolders=o.flatMap((e=>pa(e,s)))}static getRipwalkCache(){return fl.ripwalkCache??=new Wc,fl.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,ki.DN)(e)??(0,ki.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ki.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,ir.PH)(r,(async e=>{const t=await(0,ki.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=(await(0,ir.PH)(a,(async r=>{const n=await Jc(e,t,r);return null!==n&&pa(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([fl.initializeIgnoreMapping(u,".gitignore",c,i),fl.initializeIgnoreMapping(a,".cursorignore",l,i)]),new fl(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ki.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 fl.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,ti.access)(n,ti.constants.F_OK);const t=await ac(n),o=fl.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===rl(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=fl.deduplicateRootDirectories(e),i=await fl.promiseQueue.enqueueList(o,(e=>fl.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await ac(e),n=fl.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await fl.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,be.q6)(),o=[],i={root:e,includeGlobs:ol.map((e=>`**/${e}`)),excludeGlobs:[...el,...tl(e,r)],source:"ignore_scan"},a=fl.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}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=fl.parseIgnoreRules(await ac((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)=>Ec().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,ki.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,ki.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ki.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 fl.promiseQueue.enqueueList(o,(e=>fl.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,ki.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ki.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,ki.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,ti.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const n=e[t];e[t]=n?[...n,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ki.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()}dispose(){this.gitIgnoreCache=new la.q({max:1}),this.cursorIgnoreCache=new la.q({max:1}),this.gitRootCache=new la.q({max:1}),this.gitRemoteUrlCache=new la.q({max:1}),this.hasGitDirCache=new la.q({max:1}),this.directoryWalkPlacementCache=new la.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ac(e),n=fl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ac(e),n=fl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ki.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,ti.access)((0,s.join)(e,".git"),ti.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=await(this.teamSettingsService?.getTeamRepos());if(!t)return!1;const r=t.repos??[],n=t.disableLocalExecAllowlistEnforcement?[]:t.allowedRepos??[];if(0===r.length&&0===n.length)return!1;const o=await this.findGitRootsForFile(e);if(0===o.length)return this.checkNonRepoPathBlockedByAllowlist(e,n);let i=0===n.length,a=!1;for(const t of o){let o;if(this.gitRemoteUrlCache.has(t)?o=this.gitRemoteUrlCache.get(t):(o=await Zc((0,be.q6)(),this.gitExecutor,t),void 0!==o&&this.gitRemoteUrlCache.set(t,o)),void 0===o)continue;const c=o,l=(0,s.relative)(t,e)||".";for(const e of r)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;n.length>0&&!a&&(a=!0,i=n.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,ki.ZU)({basePath:r,targetPath:e}))return!1;const n=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,n))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,n))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ki.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ki.oL)((0,s.relative)(t,e)):(0,ki.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ki.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){return e.includes("*")?"*"===e.trim()||this.matchRepoUrlGlob(cl(e),cl(t)):cl(e)===cl(t)}matchGlob(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=il.get(e);if(void 0!==t)return t;let r;try{const t=xc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return al(il,2048,e,r)}(r)(t)}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();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=>this.doesRepoUrlMatch(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(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,be.q6)();for(const e of this.rootDirectories){const o=(0,ki.o1)(e);try{await(0,ti.access)((0,s.join)(o,".git"),ti.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,s.dirname)(o);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,ti.access)((0,s.join)(i,".git"),ti.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:[...r,...tl(o,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=fl.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,s.join)(o,e),n=(0,s.dirname)(r),i=(0,s.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Zc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}fl.promiseQueue=new ir.TJ({max:hl});const ml="agent-tools",gl=51380224;var wl=r("node:async_hooks");const yl=new wl.AsyncLocalStorage;function vl(e,t){return yl.run(e,t)}new wl.AsyncLocalStorage;var bl=r("../proto/dist/generated/agent/v1/utils_pb.js"),Sl=r("../utils/dist/safe-spawn-cwd.js"),kl=r("node:child_process"),_l=r("../utils/dist/workload-spawn.js");const Cl=(0,x.h)("local-exec:shell-output-encoding"),El=(0,fa.promisify)(kl.execFile),xl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,Pl=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function Il(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const Rl="㐀-䶿一-鿿豈-﫿",Tl=" -〿㈀-㏿︰-﹯＀-￯",Al="‐-※←-⇿─-◿★☆",$l="぀-ヿ",Ml=new Map([["cp932",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${Rl}${Tl}${Al}${$l}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${Rl}${Tl}${Al}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const Dl=function(e){let t,r,n,o=!1,s=0;const i=()=>{s+=1;const e=s;n=async function(){const{stdout:e}=await(0,_l.D9)(El,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const s=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=Il(t,xl),o=Il(t,Pl);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 ma.encodingExists(t)?t:void 0}(t);return void 0!==n&&Ml.has(n)?n:void 0}(s),r=s,o=!0,n=void 0,Cl.info((0,be.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:s.oemcp??"none",acp:s.acp??"none"})}),(t=>{n=void 0,Cl.warn((0,be.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&&i(),{current:()=>("win32"===e&&!o&&void 0===n&&s<3&&i(),t),pages:()=>void 0!==r?r:"win32"!==e||s>=3&&void 0===n?"none":"pending",settled:()=>n??Promise.resolve()}}(process.platform),Ol=Buffer.alloc(0),Fl=/[\u0080-\uffff]/;function Nl(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 jl(){const e=new Ic.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Ll(e,t){return ma.decode(t,e,{stripBOM:!1})}const Ul=/[\xe0-\xef][\x80-\xbf]\?/;const Bl=10,Wl=Buffer.alloc(0),Hl=new Set([7,8,9,10,11,12,13,27]);function ql(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Vl={encoding:"utf8",skip:0};function Kl(e){const t=e();let r="utf8";const n={},o=()=>"utf8"===r?t:n[r]??=Gl(r);let s,i=!0,a=Wl,c=!1,l=0;const u=(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?Vl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Vl;const n=zl(e,r);if(-1!==n)return ql(e,r,n)?{encoding:r,skip:0}:Vl;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:ql(e,r,n)?o:Vl}if(-1===i)return t?Vl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Vl:void 0;if(0===e[i+1])return o}return Vl},d=e=>{if(e===r)return"";const t=o().end();return r=e,t},h=e=>"utf8"===r&&0!==e&&e<128,p=(e,n)=>{let p="",f=e;for(;;){if(i){const e=Math.min(f.length,512-a.length);let r;if(r=a.length>0?Buffer.concat([a,f.subarray(0,e)]):e===f.length?f:f.subarray(0,e),0===r.length)return p;const o=u(r,n||r.length>=512);if(void 0===o)return 1===r.length&&h(r[0])&&(p+=t.write(r),c=!0),a=Buffer.from(r),p;let m=o.skip,g=!1;if(c&&(m="utf8"===o.encoding?1:2,g=r[0]===Bl,c=!1),0===a.length)m>0&&(f=f.subarray(m));else{const t=r.subarray(m);f=f.subarray(e),f=0===f.length?t:0===t.length?f:Buffer.concat([t,f]),a=Wl}if(i=g,l=0,s=void 0,p+=d(o.encoding),g)continue}if(0===f.length)return p;if("utf8"===r&&!f.includes(0)&&!f.includes(254)&&!f.includes(255)){const e=f.lastIndexOf(Bl),r=-1===e?-1:f.length-e-1;if(-1===r||r>=2)return p+t.write(f);if(i=!0,0===r)return e>0&&f[e-1]===Bl&&(a=Buffer.of(Bl),c=!0),p+t.write(f);const n=f[f.length-1];return a=Buffer.of(n),c=h(n),p+t.write(c?f:f.subarray(0,e+1))}const e=zl(f,r,l,s);if(-1===e)return l+=f.length,s=f[f.length-1],p+o().write(f);p+=o().write(f.subarray(0,e)),f=f.subarray(e),i=!0}};return{write:e=>0===e.length?o().write(e):p(e,!1),peek(){if(!i||0===a.length)return"";const t=u(a,!0);if(void 0===t)return"";const r=c?"utf8"===t.encoding?1:2:t.skip,n=a.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Gl(t.encoding).write(n)},end(){const e=p(Wl,!0)+o().end();return i=!0,a=Wl,c=!1,l=0,s=void 0,e}}}var Jl=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},Zl=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 Xl=(0,x.h)("local-exec:shell-core"),Ql="win32"===process.platform,Yl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function eu(e){return`'${e.replace(/'/g,"'\\''")}'`}const tu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function ru(e){return tu.some((t=>e.includes(t)))?(0,Xs.createHash)("sha256").update(e).digest("hex"):e}function nu(e,t){return e[t]??process.env[t]}const ou=/^[A-Za-z_][A-Za-z0-9_]*$/,su=/CURSOR_SANDBOX/i;function iu(e){return ou.test(e)&&!su.test(e)}function au(e){return"function"==typeof e?e():e}function cu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function lu(e){let t=0,r=0;const n=e.length;for(;riu(e)&&!r.includes(e))),o=`builtin unset ${[...Yl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Yl){const r=nu(e,t);void 0!==r&&s.push(`builtin export ${t}=${eu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${eu(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("; ")}(y,b),void 0!==y.__CURSOR_SANDBOX_ENV_RESTORE&&(y.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=ru(e);t!==e&&(r=r.split(e).join(t))}return r}(y.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,S,b.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const k=function(e,t){const r=nu(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[]}}(nu(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=cu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=cu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=cu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=cu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,y),_=(0,oi.CG)(k??oi.BM);let C,E,x;k&&(yield{type:"start",sandboxed:"workspace_readonly"===_||"workspace_readwrite"===_}),t.askpassConfig&&!Ql&&(y.SUDO_ASKPASS=t.askpassConfig.helperPath,y.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,y.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=(this.options.outputFallbackEncoding??(()=>Dl.current()))(),I=()=>function(e){if(void 0===e)return jl();const t=Ml.get(e);return void 0!==t&&ma.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=Fl.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&&Ul.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Ol,i=0,a="utf8";const c=()=>{a="utf8",o.reset(),i=0},l=(t,n)=>{const s=n?Nl(t):0,c=t.subarray(0,t.length-s),l=c.toString("utf8");if("replacement"!==a){const t=c.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===l.length?"":l[l.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,u=function(e,t,r){let n=Ll(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s{const t=0===s.length?e:Buffer.concat([s,e]);if(s=Ol,"utf8"===a){const e=t.subarray(0,t.length-Nl(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(c(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(l.length))),-1===e?o.note(n):c(),i=u;continue}a="undecided"}const{text:h,keep:p}=l(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&c(),i=u}return r},end:()=>{const e=s;s=Ol;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):l(e,!1).text;return c(),t}}}(e,t):jl()}(P),R={stdout:Kl(I),stderr:Kl(I)},T=e=>{void 0!==u&&0!==e.length&&(u.file?u.file.write(e):u.buffer+=e)},A=function*(){const e={stdout:f,stderr:m};for(const t of["stdout","stderr"]){const r=R[t].end();0!==r.length&&(void 0!==u&&!0!==u.truncated&&T(r),e[t]||(yield{type:t,data:r}))}};for await(const r of i.execute(e,t.command,{signal:w,workingDirectory:l,env:y,sandboxPolicy:k,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:au(this.options.powershellUtf8Console),powershellUtf8ChildEnv:au(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:au(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:au(this.options.powershellWebRequestUtf8)})){C=0,E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=R[r.type],o="stdout"===r.type?f:m,i=void 0===u||!0===u.truncated;let a=!1;if(!o||!i){C=r.data.length;const c="stdout"===r.type?h:p,l=!o&&c+C<=Ei,f=void 0!==u&&!0!==u.truncated&&u.size+C<=gl;"stdout"===r.type?e=l:t=l;const m=!o&&!l,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&T(x),m||(x="")),(l||f)&&(E=n.write(r.data),a=!0),void 0!==u&&u.size+C>gl)u.truncated=!0;else if(f&&void 0!==u)if(u.size+=C,u.lineCount+=lu(r.data),u.file)u.file.write(E);else if(u.buffer+=E,u.size>u.threshold){const e=s.join(this.projectDir,ml);u.path=s.join(e,`${(0,Xs.randomUUID)()}.txt`);try{await(0,ti.mkdir)(e,{recursive:!0}),u.file=(0,ni.createWriteStream)(u.path),u.file.on("error",(e=>{d??=e})),u.file.write(u.buffer)}catch(e){d??=e instanceof Error?e:new Error(String(e)),u.truncated=!0}u.buffer=""}}a||n.end()}switch(r.type){case"stdout":e?(h+=C,E&&(yield{type:"stdout",data:E})):f||(x&&(yield{type:"stdout",data:x}),f=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:oi.Ls});break;case"stderr":t?(p+=C,E&&(yield{type:"stderr",data:E})):m||(x&&(yield{type:"stderr",data:x}),m=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*A();const e=Math.max(0,Math.round(performance.now()-o));let t;if(u?.file){if(u.truncated){const e=`\n... (output truncated at ${u.size} bytes) ...\n`;u.file.write(e),u.size+=e.length,u.lineCount+=wa(e)-1}const e=await new Promise((e=>u.file.end(e)));d??=e??void 0,d?await(0,ti.rm)(u.path,{force:!0}):t=new bl.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})}d&&void 0!==u?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${u.path}: ${d.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*A()}catch(e){r.error=e,r.hasError=!0}finally{Zl(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 hu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Jl(r,(0,c.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Xl.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{Zl(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class pu{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 fu(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(aa(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function mu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return aa(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 gu(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new Ir.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new Ir.pZ({command:e,workingDirectory:t,reason:mu(r)})}}var wu=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 yu=(0,x.h)("local-exec:background-shell");function vu(e,t,r){return new xr.Lt({result:gu(e,t,r)})}class bu{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 Su(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 ku(e){e().catch((()=>{}))}class _u{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Si.L3.compile(e.config.pattern,Si.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=wi(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}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:Date.now()-this.startedAtMs}),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=me(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:`${gi(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=me(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&&yu.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 Cu{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 _u({shellId:t,outputPath:i,config:o,conversationId:r??fe,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&yu.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 Eu{async spawn(e,t){const r=new AbortController,n=new bu(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 oi.SandboxUnsupportedError||e instanceof uu)throw e}return ku((()=>Su(n,o))),n}async adopt(e){const t=new bu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,ku((()=>Su(t,e.eventIterator))),t}}function xu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Pu(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: ${xu(e.cwd)}\n`,n+=`command: ${xu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${xu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function Iu(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 Ru{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,ti.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();let g,w="running",y=!1,v=Promise.resolve();const b=async e=>{if(c)try{await c.write(e)}catch(e){}},S=t.shellId,k=s.join(r,`${S}.txt`),_=async()=>{if(!a)return;const e=Date.now()-f,r=Pu({pid:g,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},C=()=>(v=v.then(_).catch((()=>{})),v),E=()=>{void 0!==l&&(clearInterval(l),l=void 0)},x=async e=>{if(p)return;p=!0,g=e;const r=Date.now()-f,n=Pu({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:r});await(0,ti.writeFile)(k,n,"utf8"),l=setInterval((()=>{C()}),5e3)},P=async()=>{a||(a=await ni.promises.open(k,"r+")),c||(c=await ni.promises.open(k,"a"))},I=async(e,t)=>{if(!y){if(y=!0,E(),p||await x(),await P(),void 0!==t){const e=Date.now()-f,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(r)}w=e,await C()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await x(),await P()),await b(r.data);else if("stderr"===r.type)p||(await x(),await P()),await b(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 x(r.pid),await P());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`;b(`[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 x(),await P(),await b(Iu("stderr"));else d=!0,p||await x(),await P(),await b(Iu("stdout"));yield r}if(!y){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=xu(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await v,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,ti.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let i="running";const a=Date.now()-n,c=Pu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,ti.writeFile)(r,c,"utf8");const l=await ni.promises.open(r,"r+");let u;try{u=await ni.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=!1,f=!1,m=Promise.resolve();const g=async()=>{const t=Date.now()-n,r=Pu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},w=()=>(m=m.then(g).catch((()=>{})),m);let y=setInterval((()=>{w()}),5e3);const v=()=>{void 0!==y&&(clearInterval(y),y=void 0)},b=async()=>{if(!d){d=!0,v(),await m;try{await l.close()}catch{}try{await u.close()}catch{}}},S=async e=>{try{await u.write(e)}catch(e){}},k=async(t,r)=>{if(!h){if(h=!0,v(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(o)}i=t,await w()}},_={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await S(e.data):"stdout_trimmed"!==e.type||p?"stderr_trimmed"!==e.type||f?"exit"===e.type&&(await k(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await b()):(f=!0,await S(Iu("stderr"))):(p=!0,await S(Iu("stdout")))}return t.done&&await b(),t}catch(t){const r=e.abortController.signal.aborted;throw await k(r?"aborted":"failed"),await b(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}return await b(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:_})}}class Tu{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:pe(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??fe,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:Date.now()-o,...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.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},n,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.startTime,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 Au{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 $u{constructor(e,t,r,n,o,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new Au(s,i):s,c=o??function(e){const t=new Eu;return new Ru(t,e)}(n),l=new Cu(c,n,a);this.backgroundShellManager=new Tu(l,a)}getManager(){return this.backgroundShellManager}dispose(){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,c.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Ki(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ki.o1)(s),a=new Ir.HO(di(n).structured),l=ca({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new xr.Lt({result:{case:"rejected",value:new Ir.pZ({command:n,workingDirectory:i,reason:l})}});let u=o;if(yu.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}),zr(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId},o);if("block"===r.kind)return yu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),vu(n,i,r.reason);yu.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.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:Hr(t)},o);if("block"===r.kind)return yu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),vu(n,i,r.reason);u=r.policy,yu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Fi()&&(u=Wi(n,a)),u&&"insecure_none"!==u.type){const e=await ul(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}: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 xr.Lt({result:{case:"success",value:new xr.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof oi.SandboxUnsupportedError){const o=u?.type??"unknown";return yu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new xr.Lt({result:{case:"sandboxUnsupported",value:new Ir.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new xr.Lt({result:{case:"error",value:new xr.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const Mu={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Du=Ln.object({command:Ln.string().optional(),args:Ln.array(Ln.string()).optional(),env:Ln.record(Ln.string(),Ln.string()).optional(),url:Ln.string().optional(),headers:Ln.record(Ln.string(),Ln.string()).optional(),cwd:Ln.string().optional(),envFile:Ln.string().optional(),auth:Ln.object({CLIENT_ID:Ln.string(),CLIENT_SECRET:Ln.string().optional(),scopes:Ln.array(Ln.string()).optional()}).optional(),enabledTools:Ln.array(Ln.string()).optional(),placement:Ln.enum(["server","client"]).optional(),tls:Ln.object({caBundle:Ln.string().trim().min(1).max(131072)}).optional()}),Ou=Ln.object({mcpServers:Ln.record(Ln.string(),Du).optional()}),Fu=Ln.enum(["canvas"]),Nu=Ln.array(Fu).transform((e=>[...new Set(e)].sort()));class ju extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Lu(e){const t=e.trim();if(!t)throw new ju("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new ju("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new ju("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new ju("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 ju("Missing plugin name before @",e);if(!s)throw new ju("Missing source after @",e);if(!r.test(o))throw new ju("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new ju("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 ju("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 ju("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 ju("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new ju("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 ju("Missing marketplace name",e);if(!r.test(a))throw new ju("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function Uu(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 Bu(e){return e.sourceInfo.name}function Wu(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Hu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function qu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const zu=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Gu(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=>zu.has(e)))}const Vu=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Ku=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Ju=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Zu(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Ju.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Xu(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Xu(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Xu(r,t)}else for(const[,r,n,o]of e.matchAll(Vu)){const e=r??n;if(void 0===e||Ku.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Qu(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Xu(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:Zu(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.`,...Gu(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var Yu=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const ed=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),td=/^v?(\d+\.\d+(?:\.\d+)?)$/;function rd(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 nd(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=td.exec(e);if(null!==t)return t[1]}}function od(e){return void 0===e?{kind:"absent"}:ed.has(e)?{kind:"supported",id:e,version:nd(e)??e}:{kind:"unsupported",id:e}}const sd=10485760,id=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,ad=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],cd=[".cursor-plugin",".claude-plugin"],ld=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ud=Ln.object({source:Ln.literal("github"),repo:Ln.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),dd=Ln.object({source:Ln.literal("url"),url:Ln.string().url().endsWith(".git","URL must end with .git"),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),hd=Ln.object({source:Ln.literal("git-subdir"),url:Ln.string().url().endsWith(".git","URL must end with .git"),path:Ln.string().min(1),ref:Ln.string().optional(),sha:Ln.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),pd=Ln.union([Ln.string(),ud,dd,hd]),fd=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,md='Must be a semver version (X.Y.Z) or "never"',gd=Ln.object({cursor:Ln.string().regex(fd,md).optional(),sand:Ln.string().regex(fd,md).optional(),sandMobile:Ln.string().regex(fd,md).optional()}),wd=Ln.object({name:Ln.string().min(1,"Author name is required"),email:Ln.string().email().optional()}),yd=Ln.enum(["string","number","integer","boolean","object","array","null"]),vd=Ln.union([yd,Ln.array(yd).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Ln.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function bd(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Ln.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:Ln.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:Ln.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:Ln.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:Ln.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:Ln.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:Ln.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const Sd=Ln.lazy((()=>Ln.object({type:vd.optional(),title:Ln.string().optional(),description:Ln.string().optional(),format:Ln.string().optional(),writeOnly:Ln.boolean().optional(),placeholder:Ln.string().optional(),default:Ln.unknown().optional(),enum:Ln.array(Ln.any()).nonempty().optional(),const:Ln.unknown().optional(),properties:Ln.record(Ln.string(),Sd).optional(),required:Ln.array(Ln.string()).optional(),additionalProperties:Ln.union([Ln.boolean(),Sd]).optional(),items:Ln.union([Sd,Ln.array(Sd)]).optional(),minLength:Ln.number().int().nonnegative().optional(),maxLength:Ln.number().int().nonnegative().optional(),minimum:Ln.number().optional(),maximum:Ln.number().optional(),exclusiveMinimum:Ln.number().optional(),exclusiveMaximum:Ln.number().optional(),multipleOf:Ln.number().positive().optional(),minItems:Ln.number().int().nonnegative().optional(),maxItems:Ln.number().int().nonnegative().optional(),uniqueItems:Ln.boolean().optional(),minProperties:Ln.number().int().nonnegative().optional(),maxProperties:Ln.number().int().nonnegative().optional()}).strict().superRefine(bd)));function kd(e){const t=Sd.superRefine(((e,t)=>{Ed(e)&&"object"===e.type||t.addIssue({code:Ln.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?xd(t.data)?{success:!0,data:t.data}:{success:!1,error:new Ln.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const _d=Ln.unknown().superRefine(((e,t)=>{const r=kd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!xd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),Cd=(Ln.object({name:Ln.string().min(1).transform((e=>e.toLowerCase())).refine((e=>id.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ln.string().optional(),source:pd,description:Ln.string().optional(),version:Ln.string().optional(),author:wd.optional(),publisher:Ln.string().min(1).optional(),homepage:Ln.string().url().optional(),repository:Ln.string().url().optional(),license:Ln.string().optional(),keywords:Ln.array(Ln.string()).optional(),capabilities:Nu.optional(),logo:Ln.string().optional(),category:Ln.string().optional(),tags:Ln.array(Ln.string()).optional(),minClientVersions:gd.optional(),strict:Ln.boolean().default(!0),commands:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),agents:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),skills:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),rules:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),hooks:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]).optional(),variables:_d.optional(),mcpServers:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown()),Ln.array(Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]))]).optional()}),Ln.object({description:Ln.string().optional(),version:Ln.string().optional(),pluginRoot:Ln.string().optional()}),Ln.object({name:Ln.string().min(1).regex(id,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Ln.string().optional(),description:Ln.string().optional(),version:Ln.string().optional(),author:wd.optional(),publisher:Ln.string().min(1).optional(),homepage:Ln.string().url().optional(),repository:Ln.string().url().optional(),license:Ln.string().optional(),logo:Ln.string().optional(),keywords:Ln.array(Ln.string()).optional(),capabilities:Nu.optional(),minClientVersions:gd.optional(),commands:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),agents:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),skills:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),rules:Ln.union([Ln.string(),Ln.array(Ln.string())]).optional(),hooks:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]).optional(),variables:_d.optional(),mcpServers:Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown()),Ln.array(Ln.union([Ln.string(),Ln.record(Ln.string(),Ln.unknown())]))]).optional()}));function Ed(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xd(e){return Ed(e)&&"object"===e.type}function Pd(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Id(e,t){if(Ed(e)&&"string"==typeof e.name){const t=Pd(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Pd(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,Xs.randomUUID)()}`}(t)}function Rd(e){if(Ed(e)&&Ed(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 Td(e){return"string"==typeof e?e:void 0}function Ad(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function $d(e){return"string"==typeof e?e:Ad(e)}function Md(e){if(!Ed(e)||!Ed(e.metadata))return;const t={description:Td(e.metadata.description),version:Td(e.metadata.version),pluginRoot:Td(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Dd(e){if(!Ed(e))return;const t=Td(e.name);if(void 0===t||0===t.length)return;const r=Td(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Od(e){if("string"==typeof e||Ed(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Ed(e)));return t.length>0?t:void 0}}function Fd(e){if("string"==typeof e||Ed(e))return e}function Nd(e){if(void 0===e)return;const t=kd(e);return t.success?t.data:void 0}function jd(e,t={}){if(e.length>sd)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(!Ed(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(!Ed(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:Ed(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Td(n.ref),sha:Td(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Td(n.ref),sha:Td(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:Td(n.ref),sha:Td(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Td(n.ref),sha:Td(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Td(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?Pd(e.name):"")||function(e){if("string"==typeof e){const t=Pd((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Pd(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Pd((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=Pd((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=Nu.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=gd.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:Td(e.displayName),source:r,description:Td(e.description),version:Td(e.version),author:Dd(e.author),publisher:Td(e.publisher),homepage:Td(e.homepage),repository:Td(e.repository),license:Td(e.license),keywords:Ad(e.keywords),logo:Td(e.logo),category:Td(e.category),tags:Ad(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:$d(e.commands),agents:$d(e.agents),skills:$d(e.skills),rules:$d(e.rules),hooks:Fd(e.hooks),variables:Nd(e.variables),mcpServers:Od(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:Id(r,t),owner:Rd(r),description:Td(r.description),plugins:n,metadata:Md(r),skippedPluginEntries:o}}}function Ld(e){if(e.length>sd)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=od(rd(t)),n=Cd.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 Ud(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 Bd(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Wd(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new Yu.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Hd=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const qd=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,zd=/\$%7B([^%/?#]+?)%7D/gi;function Gd(e,t){return Vd(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 Vd(e,t){if("string"==typeof e)return function(e,t){return e.replace(zd,"${$1}").replace(qd,((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=>Vd(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]=Vd(o,t);return r}return e}function Kd(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Jd=[".mcp.json","mcp.json"],Zd=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Xd(e,t){if(!function(e){return Zd.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 Qd(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Yd(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Jd.map((e=>void 0!==t?`${t}/${e}`:e))}function eh(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=Kd(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Kd(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?Kd(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Kd(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Gd(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Gd(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 th(e,t,r){try{const n=(0,Hd.qg)(e),o=rd(n);if(void 0!==o){const e=r?.log??Mu;"unsupported"===od(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=nd(e),n=nd(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=Ou.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:eh(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Xd(e,t)&&Qd(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Ou.safeParse({mcpServers:a});if(e.success)return i?e.data:eh(e.data,t,r)}return null}catch{return null}}function rh(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function nh(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Jd,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=th(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(!Bd(i))return;const a=await t(i);if(null===a)return;const c=th(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&rh(s,c.mcpServers,n(i))},a=e=>{const t=th(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&rh(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}}}function oh(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}var sh=r("node:stream"),ih=r("node:stream/promises"),ah=r("node:zlib"),ch=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const lh=".cache-complete";function uh(e){return sr(e)}function dh(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function hh(e,t){return function(e,t,r,n){const o=[t,r];return void 0!==n&&o.push(n),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...o):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...o].join("/"):(0,s.join)(e,...o)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?uh(t.version):void 0)}class ph{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return hh(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=dh({parent:t,name:lh});return(await(0,ti.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,ti.mkdir)(t,{recursive:!0});const r=sh.Readable.from(e.tarball);return await(0,ih.pipeline)(r,(0,ah.createGunzip)(),(0,ch.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=hh(this.cacheRoot,e);try{return(await(0,ti.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,ti.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=hh(this.cacheRoot,e);await(0,ti.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=>uh(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,ti.writeFile)(dh({parent:t,name:lh}),"")}}function fh(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 mh=[["safe.bareRepository","explicit"]],gh=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],wh=[["core.quotePath","false"]];function yh(e){const t="allow-hooks"===e?gh.filter((([e])=>"core.hooksPath"!==e)):gh;return[...mh,...t]}const vh=(0,fa.promisify)(kl.execFile),bh=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),Sh=new Set(["diff","show","blame","log","whatchanged"]);function kh(e){for(let t=0;tArray.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});return xh("git",[...Ph(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const Th=/^[0-9a-f]{7,40}$/i,Ah=/^[0-9a-f]{40}$/i;function $h(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 Mh(e,t,r){const n=t.trim();if(Ah.test(n))return{fullSha:n.toLowerCase()};if(Th.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Rh(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return $h(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 Rh(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=$h(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 Rh(["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=$h(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Dh=ld.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 Oh;function Fh(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 Nh(e){const t=[];for(const r of e){const e=Fh(r);if(null===e)return"all";t.push(e)}return t}async function jh(e,t){const r="all"===e?"all":Nh(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Oh??=(async()=>{try{const{stdout:e}=await Rh(["--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}})(),Oh));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Dh,...o])]):[]};var o}function Lh(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Uh(e,t,r){await Rh(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Bh(e){try{await(0,ti.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Rh(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Wh(e,t,r){if("all"!==t&&0===t.length)return;if(!await Bh(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Rh(["sparse-checkout","disable"],n);const o=Nh(t);"all"!==o?await Rh(["sparse-checkout","add","--",...o],n):await Rh(["sparse-checkout","disable"],n)}(0,Pi.J)((function(){Oh=void 0}));const Hh=/\.git$/i,qh=new Set(["account","dashboard"]);function zh(e){return e.replace(Hh,"")}function Gh(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Vh(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Kh(e){return e.toLowerCase().split(".").includes("gitlab")}function Jh(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function Zh(e){const t=e.toLowerCase();return Kh(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Xh(e){return Vh(e)?"github":Kh(e)?"gitlab":Jh(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Qh(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);qc(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=zh(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:Xh(r),owner:s.owner,repo:s.repo,host:r}}function Yh(e){const t=ep(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 ep(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function tp(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Qh(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Kh(r.host)){const e=ep(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=zh(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=ep(e.trim());if(null!==t&&Jh(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Gh(t),o=Gh(r);if(void 0===n||void 0===o||qh.has(n.toLowerCase()))return;const s=zh(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=ep(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=zh(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!qc(e.host)&&null===Zh(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=np(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Yh(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Zh(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function rp(e){const t=tp(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 np(e){return Vh(e)?"github.com":e}function op(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 sp(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function ip(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}const ap=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 cp(e){const t=sr(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":ap.has(t.toLowerCase())?`_${t}`:t}const lp=18e5,up=6e5,dp={recursive:!0,force:!0,maxRetries:3},hp=["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"],pp=["enotempty: directory not empty, rename","/_staging/"],fp=["upload-pack: not our ref","server does not allow request for unadvertised object"];function mp(e){const t=String(e).toLowerCase().replaceAll("\\","/");return hp.some((e=>t.includes(e)))?"user_git_access":pp.every((e=>t.includes(e)))?"local_cache_race":fp.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function gp(e){return"object"==typeof e&&null!==e&&(!0===e.killed||gp(e.cause))}function wp(e){return gp(e)?"killed_by_budget":mp(e)}function yp(e){const t=tp(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=Qh(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:np(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const vp=new Map;class bp{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?lp:void 0}localTimeoutMs(){return this.sparsePluginClones?up:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Ih(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await jh(n?.materialize??"all",this.sparsePluginClones);await Rh(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Uh(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Rh(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Rh(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Lh(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,Xs.randomUUID)());return await(0,ti.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,ti.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,ti.rm)(t,dp),await(0,ti.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,ti.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,ti.stat)(n);r-o.mtimeMs>bp.STALE_STAGING_THRESHOLD_MS&&await(0,ti.rm)(n,dp)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,cp(e),cp(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=yp(e);return(0,s.join)(this.cacheRoot,cp(r),...n.map(cp),cp(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=yp(e);return(0,s.join)(this.cacheRoot,cp(t),...r.map(cp))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=cp(t);try{const e=await(0,ti.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,ti.rm)((0,s.join)(n,e.name),dp))))}catch{}if(void 0!==r)try{await(0,ti.rm)(r,dp)}catch{}}async ensureCloned(e,t,r,n=Mu,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,ir.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Mu){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Wh(e,t,{extraGitConfig:Ih(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:wp(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:wp(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,ir.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(vp.get(r)??Promise.resolve()).catch((()=>{})).then(t);vp.set(r,n);try{return await n}finally{vp.get(r)===n&&vp.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:rp(t);if(null!==a)try{i=(await Mh(a,s,{sshBatchMode:!0,extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&gp(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:mp(e)}),a=null,i=(await Mh(t,s,{extraGitConfig:Ih(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Mh(t,s,{extraGitConfig:Ih(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 Bh(c);return e&&await Wh(c,o,{extraGitConfig:Ih(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,ti.utimes)(l,e,e).catch((()=>{}))}),bp.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&&gp(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:wp(e)}),await(0,ti.rm)(l,dp),await(0,ti.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=wp(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,ti.rm)(l,dp)}catch{}}}async isCloneComplete(e){try{if(!(await(0,ti.stat)(e)).isDirectory())return!1;const t=await(0,ti.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,ti.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return ip(e,t)}async copyPluginToDir(e,t){await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.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 ld){const n=(0,s.join)(e,r);let o;try{o=await(0,ti.readFile)(n,"utf-8")}catch{continue}const i=jd(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=Ud(n.source,r.metadata?.pluginRoot);return o&&Bd(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=Ud(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":Bd(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):[]}}bp.STALE_STAGING_THRESHOLD_MS=3e5,bp.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const Sp=(0,fa.debuglog)("cursor-plugins");function kp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _p(e){return kp(e)?e:void 0}function Cp(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function Ep(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 xp(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Np(e,t.gitUrl)?e:r:e}function Pp(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function Ip(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=Ep(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Rp="backend-git://";function Tp(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Rp}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Ap(e){if(!e.startsWith(Rp))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 $p="backend-release://";function Mp(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${$p}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Dp(e){if(!e.startsWith($p))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 Op=/^[0-9a-f]{7,40}$/i;function Fp(e){let t;try{t=yp(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Np(e,t){if(e.trim()===t.trim())return!0;const r=Fp(e),n=Fp(t);return null!==r&&r===n}const jp=104857600;async function Lp(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(!(kp(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>kp(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>jp)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||!Up(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||!Up(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>jp)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,Xs.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,ti.mkdir)(n,{recursive:!0});const u=await(0,ti.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,ti.writeFile)(d,c),await(0,ti.mkdir)(h,{recursive:!0});let e=0,t=0;await ch.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,ti.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,ti.readdir)(e)).some((e=>cd.includes(e)))&&(a=e)}const p=await(0,ti.readdir)(a);await Promise.all(p.map((e=>(0,ti.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,ti.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function Up(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Bp{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??Mu,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new bp(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=Ih(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:rp(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 Mh(e,t,n):await Mh(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&gp(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}};for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=Ep(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=Cp({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;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,Xs.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:_p(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=xp(c,r),d=Ip(e,o),h=fh(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?Mp({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Tp(g,d,t.gitPath??void 0);const w=Pp(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Np(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:Tp(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:_p(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}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=Ap(e.downloadUrl);return!(!r||!Np(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,ti.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,ti.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${sr(t.name)}.md`,o=[];o.push(`description: ${sp(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${sp(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,ti.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,ti.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${sr(t.name)}.md`,o=t.description?`---\ndescription: ${sp(t.description)}\n---\n\n`:"";await(0,ti.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,ti.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&op(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,ti.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,ti.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,ti.mkdir)(c,{recursive:!0}),await(0,ti.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,ti.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===Dp(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)&&gp(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=Mu,n,i){const a=i?.sparsePluginClones??!1,c=a?lp:void 0,l=Dp(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Lp(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=ip(r,e.gitPath);await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,ti.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Lp(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Ap(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Mu,o,s="all",i=!1){const a=performance.now(),c=Op.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?lp:void 0,h=i?up:void 0,{sparse:p,sparseDirs:f}=await jh(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Uh(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Rh(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Rh(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Rh(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Rh(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Rh(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Rh(["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:rp(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&gp(t))throw t;await(0,ti.rm)(r,{recursive:!0,force:!0}),await(0,ti.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Lh(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);Sp("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?Nh([u.gitPath]):[],a),u.gitPath)o=ip(d,u.gitPath);else{const t=await async function(e,t){for(const r of ld){const n=(0,s.join)(e,r);let o;try{o=await(0,ti.readFile)(n,"utf-8")}catch{continue}const i=jd(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=Ud(c.source,a.metadata?.pluginRoot);return l&&Bd(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 Wh(d,Nh([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=ip(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 Wh(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,ti.mkdir)(t,{recursive:!0}),await(0,ti.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,ti.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Ih(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=Nh(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?Nh([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,Nh([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 Wp(e,t,r,n,o){return new Bp(e,t,r,n,o)}var Hp=r("node:url"),qp=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const zp=()=>({});function Gp(e,t){return qp(e,{...t,engines:{...t?.engines,js:zp,javascript:zp}})}function Vp(e,t,r){return qp.stringify({content:e,data:{}},t,r)}function Kp(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Jp(e,t){if(Object.hasOwn(e,t))return e[t]}function Zp(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?Kp(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===Jp(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Kp(t.projectPath)===a&&!0===Jp(i,e))))),r||!0!==Jp(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 Xp=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");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=Xp.Ay.load(t[1],{schema:Xp.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=Jd.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(!Bd(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(!Bd(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(!Bd(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=>nh(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:Qu(a??i),configs:l}}}function lf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function uf(e){return!!lf(e)&&(void 0===e.enabledPlugins||lf(e.enabledPlugins))}function df(e){return JSON.parse(e)}function hf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function pf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=df(await(0,ti.readFile)(n,"utf-8"));uf(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=df(await(0,ti.readFile)(o,"utf-8"));uf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}async function ff(e){try{return(await(0,ti.lstat)(e)).isSymbolicLink()}catch{return!1}}async function mf(e){if(await ff(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,ti.readFile)(e,"utf-8")}async function gf(e){if((await(0,ti.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function wf(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 yf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,ti.realpath)(e),n=ip(t,r),o=await(0,ti.realpath)(n);if(ip(t,o),!(await(0,ti.stat)(o)).isFile())return;return await gf(o),(0,Hp.pathToFileURL)(o).href}catch{return}}function vf(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 bf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Sf(e,t){return vf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function kf(e,t,r){let n;for(const o of ad){const i=(0,s.join)(e,o);let a;try{if(await ff(i))continue;if(!(await(0,ti.stat)(i)).isFile())continue;await gf(i),a=await mf(i)}catch{continue}const c=Ld(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 yf({installPath:e,logo:l.logo}),S=vf(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&&!bf(S))continue;if(!g&&!C){n=n?{...n,fields:Sf(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=Sf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||bf(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 _f(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,ti.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return ip(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,ti.realpath)(t);try{return ip(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,ti.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,ti.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 gf(i);const l=await(0,ti.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,ti.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Cf(r,o.skills,e),xf(r,o.agents,e),Pf(r,o.commands,e),Ef(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Cf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Ef(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Kd(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function xf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Tf({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Pf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Af({content:Kd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function If(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 Rf({content:e,relativePath:t}){try{const r=Gp(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:If(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Tf({content:e,relativePath:t}){try{const n=Gp(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 Af({content:e,relativePath:t}){try{const r=Gp(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 $f(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Mf(e,t,r){const n=r??$f(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of ad){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=rd(a);const c=Ld(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return nh(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Bd(t))return null;const r=(0,s.join)(e,t);try{return await ff(r)?null:(await(0,ti.stat)(r)).isFile()?(await gf(r),await mf(r)):null}catch{return null}}}(e),{fallbackFileNames:Yd(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Df(e,t,r){const n=await Mf(e,void 0,{log:r});if(n)return n;for(const n of ld){const o=(0,s.join)(e,n);try{if(!(await(0,ti.stat)(o)).isFile())continue;const n=await(0,ti.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Nf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(jf),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(!Bd(n))continue;const o=(0,s.join)(e,n);try{await gf(o);const t=th(await mf(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 Of=new Set(Object.values(Ce));function Ff(e){return Of.has(e)}function Nf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jf(e){return!(!Nf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Lf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Ff(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Kd(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Kd(e.prompt,t)}:e)));return{...e,hooks:r}}async function Uf(e,t,r,n){if("object"==typeof r){const o=Bf(r,t);return o&&"config"in o?{config:Lf(o.config,e),...void 0!==n&&{sourcePath:n}}:o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Bd(t))return;o=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else o=(0,s.join)(e,"hooks","hooks.json");try{if(await ff(o))return;if(!(await(0,ti.stat)(o)).isFile())return}catch{return}try{await gf(o),i=await(0,ti.readFile)(o,"utf-8")}catch{return}try{a=JSON.parse(i)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const c=Bf(a,t);return c&&"config"in c?{config:Lf(c.config,e),sourcePath:o}:c}function Bf(e,t){const r=function(e){if(!Me(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(Me(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"===r){const r=_t(e);return r.isValid&&_t(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===r){if(!(Nf(n=e)&&Nf(n.hooks)&&Object.keys(n.hooks).length>0))return;const r=Le(e.hooks),o=_t(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}var n}async function Wf(e,t,r,n){const o=n?.log??Mu,s=await kf(e,t,o),i={...$f(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([_f(e,s?.manifestOptions),Mf(e,r,i),Uf(e,t,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 Hf(e,t,r){const n=r?.log??Mu,o=await kf(e,t.raw,n),[s,i,a]=await Promise.all([_f(e,o?.manifestOptions),Df(e,t,n),Uf(e,t.raw,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 Wf(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 zf(e,t,r={}){const n=r.log??Mu,o=performance.now(),i=await async function(e){const t=hf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=df(await(0,ti.readFile)(r,"utf-8"));return lf(n=e)&&lf(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=hf(e),r=(0,s.join)(t,"settings.json");try{const e=df(await(0,ti.readFile)(r,"utf-8"));return uf(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 Zp(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=Zp(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,ir.PH)(c,(async e=>({workspacePath:e,settings:await pf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=Lu(e),s=await Hf(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(Lu(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}async function Gf(e){const t=e.log??Mu,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new ph(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))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,ti.mkdir)(o,{recursive:!0});try{await n.installPlugin(e,o),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,ti.rm)(o,{recursive:!0,force:!0})}catch{}throw e}s=o}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const n=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:n.message,errorType:wf(n)});const o=e.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:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:o,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,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 Vf(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 Kf(e){return Vf(e)??`path:${e.installPath}`}function Jf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Zf(e,t){const r=[];for(const o of e){const e=Uu(o.identifier),i=`plugin:${e}`,a=Bu(o.identifier),c=Wu(o.identifier),l=Hu(o.identifier),u=qu(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}(0,s.join)((0,o.homedir)(),".claude","plugins","marketplaces");const Xf=Ln.object({path:Ln.string(),name:Ln.string().optional(),description:Ln.string().optional(),globs:Ln.array(Ln.string()).optional(),alwaysApply:Ln.boolean().optional(),content:Ln.string(),environments:Ln.array(Ln.string()).optional(),disabledEnvironments:Ln.array(Ln.string()).optional()}),Qf=Xf.extend({name:Ln.string()}),Yf=Ln.object({path:Ln.string(),name:Ln.string(),description:Ln.string().optional(),tools:Ln.array(Ln.string()).optional(),model:Ln.string().optional(),prompt:Ln.string(),permissionMode:Ln.enum(["default","readonly"]).optional()}),em=Ln.object({path:Ln.string(),name:Ln.string(),description:Ln.string().optional(),argumentHint:Ln.string().optional(),content:Ln.string()}),tm=Ln.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),rm=Ln.object({config:tm,sourcePath:Ln.string().optional()}),nm=Ln.custom((e=>"object"==typeof e&&null!==e));function om(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}}Ln.object({schemaVersion:Ln.number().int(),displayName:Ln.string().optional(),description:Ln.string().optional(),authorName:Ln.string().optional(),skills:Ln.array(Xf),rules:Ln.array(Qf),agents:Ln.array(Yf),commands:Ln.array(em),mcpConfig:Ou.extend({mcpServerSourcePaths:Ln.record(Ln.string(),Ln.string()).optional()}).optional(),hooks:rm.optional(),hooksError:Ln.string().optional(),capabilities:Ln.array(Ln.string()),variablesSchema:nm.optional()}),Error;class sm extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function im(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function am(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function cm(e){try{return am(await(0,ti.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 lm(e){const t=await cm(e);return void 0===t?[]:function(e){const t=function(e){const t=am(e);if(0===t.trim().length)return{};const r=[],n=(0,Hd.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Hd._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new sm(`.cursor/settings.json contains syntax errors: ${e}`)}if(!im(n))return{};const o=n.plugins;if(void 0===o)return{};if(!im(o))return{};const s={};for(const[e,t]of Object.entries(o))im(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||om(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function um(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var dm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const hm=(0,fa.debuglog)("agent-skills-catalog-cache");function pm(e){return(0,Xs.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function fm(e){try{return(await(0,ti.stat)(e)).mtimeMs}catch{return}}function mm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const gm=[".kits","cursor-pages"],wm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},ym=[{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},wm],vm=(new Set(ym.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function bm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function Sm(e){const t=bm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return ym.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&&vm.has(o)}function km(e){return{dirPath:(0,s.join)(e,wm.configDir,wm.subdir),scope:"builtin",source:"builtin"}}const _m="canvas";function Cm(e,t){return{dirPath:(0,s.join)(km(e).dirPath,...gm),scope:"builtin",source:"builtin"}}function Em(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return bm(r.slice(n.length+1))}function xm(e,t){const r=Em(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Pm(e){return ym.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Im(e,t){return Pm(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Rm(e,t){return Pm(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Tm=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 Am(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const $m=ym.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Am(e)}[/\\\\]${Am(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Mm=/[/\\]\.cursor[/\\]rules[/\\]/i,Dm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Om=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Fm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Om.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Mm.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Dm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Nm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Nm.ripwalkCache??=new Wc,Nm.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,c.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||pa(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 Jc(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(),l=this.buildIncludeGlobs(a),u={root:this.root,includeGlobs:l,excludeGlobs:el,followSymlinks:!0,source:"nested_extensibility"},d={rules:[],skills:[],markdown:[],agents:[]},h=Nm.getRipwalkCache();try{const e=h.walk(r.ctx,u);try{for await(const t of e.lines){const e=Fm(t,a);e&&d[e].push((0,s.resolve)(this.root,t))}}finally{h.delete(u)}}catch{}return r.span.setAttribute("nested_extensibility.rules",d.rules.length),r.span.setAttribute("nested_extensibility.skills",d.skills.length),r.span.setAttribute("nested_extensibility.markdown",d.markdown.length),r.span.setAttribute("nested_extensibility.agents",d.agents.length),d}catch(e){t.error=e,t.hasError=!0}finally{Tm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const jm=new Set(["node_modules","__pycache__","dist","build"]);async function Lm({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,ti.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,ti.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,ti.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,ti.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||jm.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 Um={agentStoreSkillsDirs:[],userHomeDirectory:""};function Bm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Wm(e,t){const r=Bm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Bm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Hm(e),inAgentStore:!1}}function Hm(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 qm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Wm(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 zm=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},Gm=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 Vm=(0,x.h)("local-exec:cursor-rules");function Km(e){return"/"===e||"\\"===e}function Jm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Zm(e){return await Lm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Xm(e){let t;try{t=await ac(e)}catch(t){return{skillFilePath:e,error:h(t)}}try{return{skillFilePath:e,content:t,parsed:Gp(t)}}catch(t){return{skillFilePath:e,error:p(t)}}}async function Qm(e){const t=await Ci(e);return{...await Xm(e),realSkillFilePath:t}}function Ym(e){return rg(e.data?.environments??e.data?.metadata?.environments)??[]}function eg(e){return rg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function tg(e){return rg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function rg(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 ng(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 og(e){return gi(e,1536)}function sg(e){return!0===e.data?.alwaysApply}function ig(e){return!0===e.data?.["disable-model-invocation"]}function ag({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---`:Vp("",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 ${g(s.length)} characters; the limit is 64. Rename the skill's folder.`),m.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 ${g(i)} characters; the limit is ${g(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${g(a)} tokens; the recommended limit is ${g(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(sg(r))return new w.DX({fullPath:e,content:t,frontmatter:n,type:new w.f5({type:{case:"global",value:new w.i9}}),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),warnings:o});const s="string"==typeof r.data?.description?og(r.data.description):void 0,i=f(s,ig(r));return i?new w.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:tg(r),type:new w.f5({type:{case:"agentFetched",value:new w.Xo}})}):new w.DX({fullPath:e,content:t,frontmatter:n,type:new w.f5({type:{case:"agentFetched",value:new w.Xo({description:s})}}),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),warnings:o})}function cg({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?og(r.data.description):"",o=If(r.data?.paths??r.data?.globs),s=ig(r);return new dm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:f(n,s),environments:Ym(r),disabledEnvironments:eg(r),scopedTo:tg(r),disableModelInvocation:s})}function lg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new w.DX({fullPath:e,parseError:t,type:new w.f5({type:{case:"agentFetched",value:new w.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new dm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ug(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void lg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});ng(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ag(t)),sg(t.parsed)||e.agentSkills.push(cg(t)))}const dg=(0,fa.debuglog)("cursor-rules-service");function hg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function pg(e){return t=>(dg("%s: %O",e,t),hg())}function fg(e,t){return pm({kind:"agent-store",surface:e,roots:[...t].sort()})}function mg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function gg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new w.i9};else{const r=If(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new w.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new w.Xo({description:og(e.frontmatter.description)})}:{case:"manuallyAttached",value:new w._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 w.DX({fullPath:e.path,content:e.body,type:new w.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class wg{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=zm(t,(0,c.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,fa.debuglog)("Failed to load cursor rules from service:",e),[])))));return qm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Gm(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()}),wg.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()}}wg.CHANGE_COALESCE_MS=1e3;class yg{constructor(e,t,r,n,i,a,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Nm(r,t,(0,o.homedir)(),i),this.ignoreService=l??new dl(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Vm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,fa.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,be.q6)(),n=zm(t,(0,c.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return yg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Gm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,fa.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return yg.ripwalkCache??=new Wc,yg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(v((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,fa.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{Gm(r)}}isRuleMarkdownFile(e){return v(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Jc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=k(await ac(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else 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{Gm(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=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Jc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([a,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);const f=[...p.values()];return(await async function(e){const t=e.filter((e=>v((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,ir.PH)(t,(e=>async function(e){try{const t=await(0,ti.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await Ci(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=Jm(e.dir)-Jm(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)&&(Km(r.at(-1))||Km(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=>!v((0,s.basename)(e.fullPath))||i.has(e)))}(f.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{Gm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,ti.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ac(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return zm(t,(0,c.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Gm(t)}}toCursorRule(e){return gg({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=zm(r,(0,c.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 l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{zm(n,(0,c.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,ti.stat)(e)).isFile()){const t=b({content:await ac(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{Gm(n)}}async isCursorIgnored(e){try{const t=await ll((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=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=k(await ac(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{Gm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.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{Gm(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=yg.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,s.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{zm(r,(0,c.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,ti.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Gm(r)}}}class vg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[]){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.getEnabledSkills=p,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=km(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:Cm(r).dirPath,this.workspaceCatalogKey=pm({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 Nm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const f=performance.now();let m=!1,g=!1,w=!1;const y=this.loadAll(e,l).then((t=>{try{Vm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-f),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:m})}catch{}return t})).catch((e=>(g=!0,pg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=y;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(w=!0,this._loaded!==t?this._loaded:(g&&this.closeSeedWindow(e),void 0===r?y:(m=!0,r)))));this.seededLoaded=t,this._loaded=t,y.then((r=>{this._loaded===t?g?w&&this.closeSeedWindow(e):(this._loaded=y,m&&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(!mm(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]))&&mm(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 fm(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=>w.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>dm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void hm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void dg("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 fm(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=>{dg("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 Im(r,e))t.add(n.dirPath)}for(const r of Rm(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(xm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Em(e,t);return void 0!==r&&2===r.length&&r[0]===_m&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return Sm(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,be.q6)(),n=zm(t,(0,c.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Gm(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,ir.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(pg("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&&xm(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=zm(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>mg(o,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>mg(o,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,t))))return void this.reload(n.ctx);const i=this._loaded,a=(async()=>{const e=await i,{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([o]));if(this.isIgnoredSkillPath(o)||this.isPrunedByExtensibilityScan(o))return r;const s=t.get(o);if(void 0===s){try{await(0,ti.stat)(o)}catch{return r}return await this.loadAll(n.ctx)}let a;try{a=await(0,ti.realpath)(o)}catch{return await this.loadAll(n.ctx)}if(a!==s)return await this.loadAll(n.ctx);try{return ug(r,{...await async function(e){const t=await ac(e);return{skillFilePath:e,content:t,parsed:Gp(t)}}(o),realSkillFilePath:a},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(pg("Failed to load Agent Skills at path"));this._loaded=a,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Gm(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,ir.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(fg(this.surface,e),r))}),(e=>{dg("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(fg(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=hg(),r=(await Promise.all(e.map((e=>Zm(e))))).flat().filter((e=>!Sm(e))),n=await Promise.all(r.map((e=>Qm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ug(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=zm(r,(0,c.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{dg("Failed to discover nested agent skills: %O",e)}))))),l=new Set(this.getAgentStoreSkillRoots()),u=await Promise.all(this.foldersToWatch.filter((e=>!l.has(e))).map((async e=>{const t=(await Zm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Qm(e))))}))),d=new Set;for(const e of u)for(const t of e)if(!d.has(t.realSkillFilePath))if(d.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),lg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(ng(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ag(t)),sg(t.parsed)||s.push(cg(t))}const h=(await a).flatMap((e=>e?.skills??[])).filter((e=>!Sm(e))),p=await Promise.all(h.map((e=>Ci(e)))),f=[];for(const[e,t]of h.entries()){const r=p[e];d.has(r)||(d.add(r),f.push(t))}const m=await Promise.all(f.map((e=>Qm(e))));for(const e of m)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),lg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(ng(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ag(e)),sg(e.parsed)||s.push(cg(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{Gm(r)}}}function bg(e){let t;switch(e.type){case"global":t=new w.f5({type:{case:"global",value:new w.i9}});break;case"fileGlobbed":t=new w.f5({type:{case:"fileGlobbed",value:new w.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new w.f5({type:{case:"agentFetched",value:new w.Xo({description:og(e.description??"")})}});break;case"manuallyAttached":t=new w.f5({type:{case:"manuallyAttached",value:new w._u}});break;default:e.type,t=new w.f5({type:{case:"manuallyAttached",value:new w._u}})}return new w.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 Sg{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{Vm.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,fa.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,ir.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Vm.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=zm(r,(0,c.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 Zf(e,(e=>e.skills))}(e),a=function(e){return Zf(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(bg(e));for(const t of e){const e=`plugin:${Uu(t.identifier)}`,r=Bu(t.identifier),n=Wu(t.identifier),o=Hu(t.identifier),a=qu(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===Gp(c.content).data?.["disable-model-invocation"]}catch{}i.push(new dm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:og(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{Gm(r)}}}const kg=(0,fa.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()?yn.b$.READONLY:yn.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 Ig(e,t){return await Lm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Rg{constructor(e,t,r="workspace",n=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,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 Ig(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,ti.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await ac(r));if(!o)continue;t.push(new yn.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=Bu(n.identifier),o=Wu(n.identifier),i=Hu(n.identifier),a=qu(n.identifier);for(const c of n.agents){const l=Jf(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?yn.b$.READONLY:yn.b$.DEFAULT;t.push(new yn.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}}var Mg=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const Dg=kl.execFile;function Og(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,_l.D9)(Dg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Mg.w3.UNSPECIFIED,Mg.w3.LEFT,Mg.w3.MIDDLE,Mg.w3.RIGHT,Mg.w3.BACK,Mg.w3.FORWARD,Mg.Dh.UNSPECIFIED,Mg.Dh.UP,Mg.Dh.DOWN,Mg.Dh.LEFT,Mg.Dh.RIGHT;const Fg=(0,fa.promisify)(kl.execFile);function Ng(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 jg(e){const{stdout:t}=await(0,_l.D9)(Fg,"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:Ng(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Mg.w3.UNSPECIFIED,Mg.w3.LEFT,Mg.w3.MIDDLE,Mg.w3.RIGHT,Mg.w3.BACK,Mg.w3.FORWARD,Mg.Dh.UNSPECIFIED,Mg.Dh.UP,Mg.Dh.DOWN,Mg.Dh.LEFT,Mg.Dh.RIGHT;const Lg={pattern:"[\\w-]{1,64}",next:e=>e},Ug={pattern:"[0-9a-f-]{36}",next:()=>Xs.randomUUID()},Bg={pattern:"webp",next:()=>"webp"},Wg={native:[Ug,Bg],agent:[Lg,Ug,Bg],legacyNative:[Ug,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Wg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Lg.pattern}$`),Mg.Z8.NATIVE_X11,Mg.Z8.XDOTOOL,(0,P.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,P.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,P.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,P.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,x.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,P.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Hg=r("../proto/dist/runtime/compact.js");Hg.HL;var qg=(0,Hg.QT)(ar.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);ar.proto3,ar.proto3,ar.proto3,ar.proto3;class zg{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 Gg={left_ptr:qg.ARROW,arrow:qg.ARROW,default:qg.ARROW,top_left_arrow:qg.ARROW,hand:qg.POINTER,hand1:qg.POINTER,hand2:qg.POINTER,pointer:qg.POINTER,pointing_hand:qg.POINTER,xterm:qg.TEXT,ibeam:qg.TEXT,text:qg.TEXT,watch:qg.WAIT,wait:qg.WAIT,progress:qg.WAIT,left_ptr_watch:qg.WAIT,crosshair:qg.CROSSHAIR,cross:qg.CROSSHAIR,tcross:qg.CROSSHAIR,move:qg.MOVE,fleur:qg.MOVE,size_all:qg.MOVE,sb_v_double_arrow:qg.RESIZE_NS,v_double_arrow:qg.RESIZE_NS,ns_resize:qg.RESIZE_NS,row_resize:qg.RESIZE_NS,top_side:qg.RESIZE_NS,bottom_side:qg.RESIZE_NS,sb_h_double_arrow:qg.RESIZE_EW,h_double_arrow:qg.RESIZE_EW,ew_resize:qg.RESIZE_EW,col_resize:qg.RESIZE_EW,left_side:qg.RESIZE_EW,right_side:qg.RESIZE_EW,top_left_corner:qg.RESIZE_NWSE,bottom_right_corner:qg.RESIZE_NWSE,nwse_resize:qg.RESIZE_NWSE,size_fdiag:qg.RESIZE_NWSE,top_right_corner:qg.RESIZE_NESW,bottom_left_corner:qg.RESIZE_NESW,nesw_resize:qg.RESIZE_NESW,size_bdiag:qg.RESIZE_NESW,not_allowed:qg.NOT_ALLOWED,no_drop:qg.NOT_ALLOWED,forbidden:qg.NOT_ALLOWED,circle:qg.NOT_ALLOWED,grab:qg.GRAB,openhand:qg.GRAB,grabbing:qg.GRABBING,closedhand:qg.GRABBING};class Vg{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 zg(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=qg.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 Og("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 Og("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Gg[t]??qg.ARROW}try{const e=await Og("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Gg))if(e.toLowerCase().includes(t))return r}catch{}return qg.ARROW}catch{return qg.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,x.h)("computer-use-lazy");var Kg=r("node:net");function Jg(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 Zg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Xg=Ln.object({rpcSocketPath:Ln.string().min(1).optional(),appControlSocketPath:Ln.string().min(1).optional(),pid:Ln.number().int().positive().optional().catch(void 0),protocolMajor:Ln.number().int().positive().optional().catch(void 0)}).passthrough(),Qg=Ln.object({data:Ln.string(),mimeType:Ln.string().min(1)}).strip(),Yg=Ln.object({message:Ln.string(),screenshot:Qg.optional(),screenshotBefore:Qg.optional(),structuredContent:Ln.unknown().optional(),isError:Ln.boolean()}).strip(),ew=Ln.object({accessibilityTrusted:Ln.boolean(),screenRecordingGranted:Ln.boolean()}).strip(),tw=Ln.union([Ln.object({id:Ln.number().int(),result:Yg,ok:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),sessionId:Ln.string().min(1),ok:Ln.literal(!0).optional(),result:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),ok:Ln.literal(!0),result:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int().nullable().optional(),error:Ln.string().min(1),errorCode:Ln.string().min(1).optional(),result:Ln.never().optional(),ok:Ln.never().optional(),permissionStatus:Ln.never().optional(),sessionId:Ln.never().optional()}).strip(),Ln.object({id:Ln.number().int(),permissionStatus:ew,result:Ln.never().optional(),ok:Ln.never().optional(),error:Ln.never().optional(),errorCode:Ln.never().optional(),sessionId:Ln.never().optional()}).strip()]);function rw(e,t){try{return JSON.parse(e)}catch{throw new Zg(`local-cua ${t} is not valid JSON`)}}const nw={responseMaxBytes:33554432,parseServiceState(e){const t=Xg.safeParse(rw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Zg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=tw.safeParse(rw(e.toString("utf8"),"RPC response"));if(!r.success)throw new Zg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Zg("local-cua RPC response ID did not match");return r.data}};class ow extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function sw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Jg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const iw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),aw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class cw{constructor(e){this.mode=e}static isInstalled(){if((0,ni.existsSync)(cw.serviceExecutablePath()))return!0;let e;try{e=nw.parseServiceState((0,ni.readFileSync)(cw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||cw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await cw.readServiceState(),t=e?.pid;return void 0!==t&&cw.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!==cw.protocolMajor&&void 0!==e.pid&&!cw.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;cw.throwIfAborted(e.signal);const t=(0,Xs.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:cw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw cw.rpcError(r);if(void 0===r.sessionId)throw new ow("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 cw.readServiceState();if(void 0===e)return;const r=await cw.sendOnce(cw.socketPathFrom(e),{id:cw.requestID,method:"control/release",requestID:(0,Xs.randomUUID)(),mode:this.mode,sessionId:t},cw.defaultCallTimeoutMs);if(void 0!==r.error)throw cw.rpcError(r)}catch(t){cw.logger.warn(e,"local-cua control release failed",{error:sw(t)})}}}async callTool(e,t,r){cw.throwIfAborted(e.signal);const n=cw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:cw.requestID,method:"tools/call",requestID:(0,Xs.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 cw.rpcError(o,t);const s=o.result;if(void 0===s)throw new ow(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new ow(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=cw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);cw.throwIfAborted(e.signal);try{return await cw.sendOnce(o,t(),n,e.signal)}catch(o){if(!cw.isPreDeliveryConnectionError(o))throw o;cw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:cw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return cw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await cw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new ow(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(cw.throwIfAborted(e.signal),!t){const e=await cw.readServiceState();if(e&&!cw.isExitedIncompatibleHelper(e))return cw.socketPathFrom(e)}await this.launchAndWait(e);const r=await cw.readServiceState();if(!r)throw new ow("local-cua sidecar did not publish service.json after launch");return cw.socketPathFrom(r)}static setLaunchGuard(e){cw.launchGuard=e}async launchAndWait(e){const t=cw.serviceAppPath(),r=cw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){cw.logger.info(e,"launching local-cua sidecar",cw.sidecarLaunchLogFields(t)),"1"===process.env[cw.directLaunchEnv]?await cw.spawnSidecarProcess(e,cw.serviceExecutablePath(),[],{detached:!0}):await cw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+cw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...cw.sharedInstallRelativePath,`${cw.serviceAppBundleName}.app`)}static helperIdentity(){const e=cw.serviceAppPath(),t=process.env[cw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=cw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,ni.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&&aw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??cw.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:iw.get(i.bundleIdentifier))??cw.appSupportFolder)};return(0,ni.existsSync)(a)&&(cw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${cw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,Xs.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[cw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return sw(e)}static socketError(e){const t=sw(e);return new ow(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return cw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,kl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new ow(`local-cua sidecar launch failed: ${cw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{cw.logger.warn(e,"local-cua sidecar process error after launch",{error:cw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,ti.readFile)(cw.serviceStatePath(),"utf8");return nw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Zg)return;throw new ow("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==cw.protocolMajor)throw new ow(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${cw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new ow("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw cw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(cw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Kg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new ow("local-cua RPC aborted"):cw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new ow(`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(cw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>nw.responseMaxBytes)return void d((()=>s(new ow("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=nw.parseResponse({line:n,expectedID:cw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new ow("local-cua RPC connection failed after request delivery")):()=>s(cw.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 ow(e))))})))}))}}let lw;function uw(){if(void 0===lw){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 lw===e&&(lw=void 0),t}));lw=e}return lw}cw.logger=(0,x.h)("local-cua:rpc"),cw.serviceAppBundleName="Cursor Computer Use",cw.appSupportFolder="cursor-computer-use",cw.productionExecutableName="CUCursorService",cw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],cw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",cw.serviceAppOverrideEnv="CUA_SERVICE_APP",cw.directLaunchEnv="CUA_DIRECT_LAUNCH",cw.protocolMajor=1,cw.defaultCallTimeoutMs=45e3,cw.launchReadyTimeoutMs=8e3,cw.launchPollIntervalMs=200,cw.requestID=1;var dw=r("node:module"),hw=r.t(dw,2);const pw="mac-webp-runtime.cjs";function fw(e){return"function"==typeof e}function mw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function gw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(mw):[]}let ww,yw;function vw(){return ww??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=gw()[0]?.getFileName();return function(){const e=hw;if("createRequire"in e&&fw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&fw(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}})(),ww}function bw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(yw??=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 gw()){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,Hp.fileURLToPath)(n):n);r((0,s.join)(t,pw)),r((0,s.join)(t,"..","..","src","computer-use",pw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),pw)),r((0,s.join)(process.cwd(),"src","computer-use",pw)),r((0,s.join)(process.cwd(),"computer-use",pw));try{const e=(0,s.dirname)(vw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",pw)),r((0,s.join)(e,"dist","computer-use",pw))}catch{}for(const t of e)try{const e=vw()(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")}(),yw)}function Sw(...e){return t=["@jsquash","webp",...e].join("/"),vw().resolve(t);var t}async function kw(...e){var t;return await(t=(0,Hp.pathToFileURL)(Sw(...e)).href,bw()(t))}const _w=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Cw=(_w((async()=>{const e=await kw("decode.js");return await e.init({wasmBinary:await ni.promises.readFile(Sw("codec","dec","webp_dec.wasm"))}),e})),_w((async()=>{const[e,t,r]=await Promise.all([kw("utils.js"),kw("meta.js"),kw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await ni.promises.readFile(Sw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Ew="image/png",xw={async normalize(e){if(e.mimeType!==Ew)throw new Error(`Mac screenshot must be ${Ew}, received ${e.mimeType}`);const t=await uw(),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 Cw(),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}},Pw={userFacing:function(e){if(e instanceof ow&&e.userFacing&&e.message.trim().length>0&&!Jg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof ow&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Iw=new Set(["keys"]),Rw=new Set(["matched","mismatch","unchecked"]),Tw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Aw=new Set(["matched"]),$w=new Set(["too_long"]),Mw=new Set(["watched","fell_back","unavailable","over_budget"]);class Dw{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??Pw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Dw.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:Dw.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:Dw.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:Dw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Dw.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:Dw.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===Mg.EB.DOWN||t.value.stroke===Mg.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 Mg.ks({result:{case:"success",value:new Mg.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=Dw.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=Dw.cursorFromResult(e)??Dw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Dw.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",Rw),a=o("unchecked",Tw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Aw.has(i)&&!c||"unchecked"===i&&void 0!==a&&$w.has(a);return new Mg.qA({method:o("method",Iw)??"",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",Mw)})}async errorResult(e){let t;if(Dw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:sw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Dw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:sw(e)})}const r=this.errors.userFacing(e);return new Mg.ks({result:{case:"error",value:new Mg.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 Mg.ks({result:{case:"error",value:new Mg.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Mg.ks({result:{case:"error",value:new Mg.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Dw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Dw.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 xw.normalize(e),failed:!1}}catch(r){const n=sw(r);return Dw.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 Mg.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 Mg.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()}))}}Dw.logger=(0,x.h)("local-cua:actions"),Dw.mouseButtonNames={[Mg.w3.UNSPECIFIED]:"left",[Mg.w3.LEFT]:"left",[Mg.w3.RIGHT]:"right",[Mg.w3.MIDDLE]:"middle",[Mg.w3.BACK]:"left",[Mg.w3.FORWARD]:"left"},Dw.scrollDirectionNames={[Mg.Dh.UNSPECIFIED]:"down",[Mg.Dh.UP]:"up",[Mg.Dh.DOWN]:"down",[Mg.Dh.LEFT]:"left",[Mg.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,x.h)("local-cua:windows");var Ow;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"]),function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Ow||(Ow={}));var Fw=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 Nw{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}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,c.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Pr.Pi({result:{case:"error",value:new Pr.GU({path:n,error:_i})}});const o=(0,ki.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await fu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Pr.Pi({result:{case:"rejected",value:new Pr.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Pr.Pi({result:{case:"permissionDenied",value:new Pr.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,ti.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,ti.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ki.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),l=await this.pendingDecisionProvider.requestApproval({type:Ow.Delete,details:{path:a},toolCallId:t.toolCallId});if(!l.approved)return new Pr.Pi({result:{case:"rejected",value:new Pr.iq({path:o,reason:l.reason||""})}});let u;try{u=await(0,ti.stat)(o)}catch(e){return"ENOENT"===rl(e)?new Pr.Pi({result:{case:"fileNotFound",value:new Pr.n0({path:o})}}):new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:nl(e)})}})}if(!u.isFile()){const e=u.isDirectory()?"directory":"other";return new Pr.Pi({result:{case:"notFile",value:new Pr.LX({path:o,actualType:e})}})}const d=u.size;let h;if(d<=xi)try{h=await ac(o)}catch{}const p=h??"",f=await(0,ti.stat)(o).catch((()=>{}));if(f?.dev!==u.dev||f.ino!==u.ino)return new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,ti.unlink)(o)}catch(e){return"EACCES"===rl(e)?new Pr.Pi({result:{case:"permissionDenied",value:new Pr.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===rl(e)?new Pr.Pi({result:{case:"fileBusy",value:new Pr.vX({path:o})}}):new Pr.Pi({result:{case:"error",value:new Pr.GU({path:o,error:nl(e)})}})}if(this.fileChangeTracker&&void 0!==h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(o,h,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Pr.Pi({result:{case:"success",value:new Pr.fl({path:o,deletedFile:o,fileSize:BigInt(d),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Fw(r)}}}class jw{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===Lt));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 ps.I0({serverIdentifier:Lt,serverName:Lt,instructions:`User-defined tools for this session (server "${Lt}"). 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 Lw extends jw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Uw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Bw=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 Ww{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,c.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new Uw.uN({result:{case:"success",value:new Uw.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Uw.uN({result:{case:"error",value:new Uw.fk({url:n,error:nl(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Bw(r)}}}class Hw{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){const o=this.changes.get(e);if(o){const t=o.before,s=n||o.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:s};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}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,ti.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 uc(e,t,r,n);await(0,ti.writeFile)(e,o),await lc(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()}}class qw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const zw=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),Gw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],Vw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,Kw=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Jw=new Set(["system","global","command"]),Zw={GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",GIT_SSH_COMMAND:"ssh -o BatchMode=yes",GCM_INTERACTIVE:"Never",GIT_EDITOR:":",GIT_SEQUENCE_EDITOR:":",GIT_OPTIONAL_LOCKS:"0",GIT_LFS_SKIP_SMUDGE:"1",GIT_CONFIG:void 0};function Xw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const Qw=Xw([...yh("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 Yw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function ey(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ty(){const e=new Map;return{async exec(t,r,n){const o=Yw(n);return xh("git",await ry(e,t,r,o),{cwd:t,env:Zw,windowsHide:!0,killSignal:"SIGTERM",timeout:ey(o)})},async run(t,r,n){const o=Yw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Ch(t);return(0,kl.spawn)("git",s,{...o,env:Eh(s,n)})}(0,t,{cwd:e,env:Zw,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"})))}),ey(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 ry(e,t,r,o),o,n?.input)}}}async function ry(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Ch(e),r=kh(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=zw.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=[...Gw,..."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),...Qw],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 xh("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Zw,windowsHide:!0,killSignal:"SIGTERM",timeout:ey(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new qw("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 qw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new qw("read-failed",t)}(e)}if(performance.now()>=r)throw new qw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new qw("read-failed");const r=new Set;for(let e=0;eXw([[`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 ny(e,t,r){return ty().exec(e,t,r)}var oy=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 sy{async exec(e,t,r,n){return iy(e,t,r,n,ny)}forRequest(){const e=ty();return{exec:(t,r,n,o)=>iy(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function iy(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,c.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{oy(s)}}var ay=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class cy{constructor(){this.lineEnd=0,this.nextStart=0}}function ly(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 uy(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 dy=-(2**31),hy=2**31-1;function py(e){return Number.isNaN(e)?0:ehy?hy:e}function fy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return py(Math.trunc(e))}var my=r("../mcp-core/dist/transport/mcp-url-utils.js");function gy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function wy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function yy(e,t,r){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){return!0===e.url?.startsWith("mcp-provider://")}(e))return!0;const n=t.allowedMcpServers??[];return 0===n.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){const n=r?.matchesServerUrlPattern??my.vc;return t.some((t=>{const r=gy(t.command),o=wy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,my.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t,r)}(e,n,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){const n=r?.matchesServerUrlPattern??my.vc;return(t??[]).some((t=>{const r=gy(t.command),o=wy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,my.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t.deniedMcpServers,r)}var vy=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 by extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Sy extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class ky extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class _y{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new by(t);return await o(e,r)}}class Cy{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,c.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new Sy(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{vy(s)}}}class Ey{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,Xs.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,ti.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,ti.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,ti.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var xy=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},Py=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 Iy{async load(e,t,r,n,o){const s=o(e,r);return new Ty(e,t,s,r)}}function Ry(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Ty{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,c.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=xy(t,(0,c.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=xy(s,(0,c.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{Py(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=xy(r,(0,c.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{Py(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=Ry(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{Py(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=xy(n,(0,c.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{Py(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=xy(t,(0,c.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{Py(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function Ay(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $y(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 My(e){return e?` (${$y(e,"")})`:""}function Dy(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=Dy(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=Dy(n);if(void 0===e)return;r[t]=e}return r}function Oy(e){const t=Dy(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const Fy=new TextDecoder("utf-8",{fatal:!0});function Ny(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function jy(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=Fy.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=Ny(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: ${$y(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const Ly=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function Uy(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function By(e){if(!Ay(e))return;const t=e.resource;return Ay(t)&&void 0===Uy(t)&&"string"==typeof t.blob&&Ly.has(Ny(t.mimeType))?t.blob:void 0}function Wy(e){const t=e,r=t.resource;if(Ay(r)){const e=Uy(r);return void 0!==e?e:"string"==typeof r.blob?jy(r,r.blob).text:`Resource: ${$y(r.uri,"unknown")}${My(r.name)}`}return t.uri?`Resource: ${$y(t.uri,"unknown")}${My(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function Hy(e){const t=Oy(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var qy=r("zod/v4-mini");const zy=qy.object({CLIENT_ID:qy.string(),CLIENT_SECRET:qy.optional(qy.string()),scopes:qy.optional(qy.array(qy.string()))}),Gy=qy.strictObject({caBundle:qy.string().check(qy.trim(),qy.minLength(1),qy.maxLength(131072))}),Vy=qy.object({type:qy.optional(qy.literal("stdio")),command:qy.string(),args:qy.optional(qy.array(qy.string())),env:qy.optional(qy.record(qy.string(),qy.string())),envFile:qy.optional(qy.string()),cwd:qy.optional(qy.string()),enabledTools:qy.optional(qy.array(qy.string())),startupTimeoutSec:qy.catch(qy.optional(qy.number().check(qy.positive())),void 0)}),Ky=qy.object({type:qy.optional(qy.enum(["http","sse"])),url:qy.string(),headers:qy.optional(qy.record(qy.string(),qy.string())),auth:qy.optional(zy),tls:qy.optional(Gy),placement:qy.optional(qy.enum(["server","client"])),enabledTools:qy.optional(qy.array(qy.string()))}),Jy=qy.union([Vy,Ky]),Zy=qy.object({mcpServers:qy.record(qy.string(),Jy)});Error;const Xy=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Qy(e,t){if("string"==typeof e)return function(e,t){return e.replace(Xy,((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=>Qy(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Qy(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 Yy(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const ev=Yy({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),tv=Yy({caBundle:"ca_bundle"}),rv=Yy({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),nv=Yy({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),ov=(new Map([["auth",{keys:ev,unknownKeyIsError:!1}],["tls",{keys:tv,unknownKeyIsError:!0}]]),"enabled");new Set([...rv.jsonKeyOf.keys(),...nv.jsonKeyOf.keys(),ov]);Symbol("disabled");const sv=(0,x.h)("McpConfig");async function iv(e,t=e=>process.env[e]){try{const r=await(0,ti.readFile)(e,"utf8"),n=Qy((0,Hd.qg)(r),t);return Zy.parse(n)}catch{return{mcpServers:{}}}}async function av(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function cv(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await av(0,t);return n.length>0&&sv.warn((0,be.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 lv=["enterprise","project","user","env"];function uv(e){return"project"===e||"env"===e}const dv=["0.0.0.0/0","::/0"];function hv(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,my.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function pv(e){const t=!0===e.enabled,r=hv(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...dv];const t=hv(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...dv]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...dv];const r=(0,my.b6)(e);return r.includes("*")?[...dv]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class fv 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 mv=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class gv extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class wv 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 yv(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function vv(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&&mv.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(!yv(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 wv;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 wv;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 gv;return e(i,a)}}function bv(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)&&Rv(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=_v(e,n),s=Pv(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:_v(e,"cause"),l=Pv(c,t,r),u=e instanceof AggregateError?_v(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>Pv(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])=>kv(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(Ev(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[Cv];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=$v(e);return void 0!==g&&$v(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 Sv(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 kv(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function _v(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const Cv=Symbol.for("nodejs.util.inspect.custom");function Ev(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 xv(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return bv(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>xv(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:xv(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function Pv(e,t,r){if(e instanceof Error)return bv(e,t,r);try{return Rv(e,t)?xv(e,t,1,r):e}catch{return}}const Iv=4096;function Rv(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=Iv||n.length>Iv)return Tv(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((Av(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(_v(s,"message"),_v(s,"stack"),_v(s,"cause")),s instanceof AggregateError&&n.push(_v(s,"errors")));for(const e of Object.keys(s))n.push(_v(s,e))}}return!1}function Tv(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,_v(n,e)]))),message:_v(n,"message"),stack:_v(n,"stack"),cause:_v(n,"cause"),...n instanceof AggregateError?{errors:_v(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function Av(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 $v(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const Mv=/spt_[A-Za-z0-9_]{6,}/g,Dv=/[A-Z0-9]/;function Ov(e){return function(e){return e.replace(Mv,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&Dv.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var Fv=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set([1,2]);const Nv="cursor/requiresConfirmation",jv="https://grok.com/connectors-oauth-exchange-code/",Lv="https://x.com/i/connectors/oauth_callback",Uv="https://chat.x.com/connectors/oauth_callback",Bv="https://lite.x.com/i/connectors/oauth_callback",Wv={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},Hv={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[jv,Lv]},qv="x-cursor-auth";function zv(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 Gv="https://mcp.shop.com",Vv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Kv=new Map([["mcp.slack.com",{gate:"mcp_oauth_scope_step_up",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/}]]),Jv=new Map([["gmailmcp.googleapis.com",{...Wv,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",{...Wv,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Wv,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",{...Wv,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Wv,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Wv,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Wv,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",Hv],["mcp.money-staging.x.com",Hv],["mcp.money.x.com",Hv],["connectors-gateway.grok.gcp.mouseion.dev",Vv],["connectors-gateway.grok.com",Vv],["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.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","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:Gv}}]]),Zv=[".cloud.databricks.com",".azuredatabricks.net",".gcp.databricks.com"];const Xv=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Qv={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Yv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0};function eb(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(".."))&&Zv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Qv:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Xv.test(e.pathname.replace(/\/+$/,""))}(t)?Yv:(r=t.hostname,Jv.get(r.toLowerCase()));var r}function tb(e){return e.endsWith("/")?e:`${e}/`}async function rb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!tb(r.pathname).startsWith(tb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const nb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function ob(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function sb(e,t){if(void 0===t)return;const r=new URL(e),n=ob(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!nb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function ib(e){const t=ob(e);return void 0===t?void 0:Kv.get(t.hostname.toLowerCase())}const ab=new Set([...Jv].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),cb="https://www.cursor.com/bot/mcp/oauth/callback",lb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:cb},ub="tailnet_";new Set([`${ub}waiting_for_approval`,`${ub}tailnet_locked`,`${ub}joining`]);const db="grokbot://mcp/oauth/callback",hb="http://localhost:8787/callback",pb="gb";new Set(["outlook","outlook-calendar","onedrive","teams"]),new Set(["teams"]);function fb(e){const t=new URL(hb);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 gb(e){const t=e.redirectUrl??hb;if(!0!==e.loopbackIpv4||!mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function wb(e,t=lb){const r=new Set,n=void 0!==e&&mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===db&&r.add(t.grokBotBounce),r.add(hb),e&&n&&r.add(e),Array.from(r)}new Map([[pb,db],["gw",jv],["gd",hb],["xa",Lv],["xc",Uv],["xl",Bv],...[18787,28787,31787].map((e=>[`gd${e}`,fb(e)]))]),new Map([[db,pb],[cb,pb],[jv,"gw"],[Lv,"xa"],[Uv,"xc"],[Bv,"xl"]]),gb({loopbackIpv4:!0}),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const yb=new Set([429,502,503,504]);function vb(e){return"object"==typeof e&&null!==e}function bb(e){const t=vb(e)?e.code:void 0,r=(e instanceof Error||vb(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&&yb.has(o)&&!yb.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}const Sb=8192;function kb(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==zv(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const _b=/\$\{[^}]*\}/;function Cb(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&_b.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const Eb=new Map;async function xb(e,t=fetch){if(void 0===zv(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=Eb.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 Eb.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Pi.J)((function(){Eb.clear()}));const Pb={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function Ib(e){return Pb}const Rb=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Tb=["invalid_request","invalid_token","insufficient_scope"];function Ab(e){return Tb.some((t=>t===e))}function $b(e){const t=[];for(const r of e){if(t.length>=20)break;r.length>0&&r.length<=200&&Rb.test(r)&&!t.includes(r)&&t.push(r)}return t}const Mb=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,Db=/"((?:[^"\\]|\\.)*)"?/y,Ob=/[^\s,]*/y;function Fb(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 Lb(e){if("object"!=typeof e||null===e||Array.isArray(e))return Nb;const t=jb("grantedScopes"in e?e.grantedScopes:void 0),r=jb("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:jb("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:jb("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ub(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function Bb(e,t){return e.filter((e=>!t.has(e)))}const Wb={stepUpScopes:[],recordRequestedScopes:async()=>{}};function Hb(e){const t=ib(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=Ib(e.accountKey);let o;const s=async()=>Lb(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ub(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=Fb(t,"error")?.toLowerCase(),n=Fb(t,"resource_metadata");return{error:void 0===r||""===r?"none":Ab(r)?r:"other",scopes:$b((Fb(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 ab.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl)||!await e.isEnabled())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 $b(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(){if(!await e.isEnabled())return Wb;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:Ub(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Lb(n),s=Ub(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=Bb(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:Bb(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}=Lb(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function qb(e){const t=ib(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function zb(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:qb(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 Gb extends Error{constructor(e,t,r){super(zb({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 zb({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Vb(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}}var Kb=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Jb="2026-07-28",Zb=-32022,Xb="io.modelcontextprotocol/protocolVersion",Qb="io.modelcontextprotocol/clientCapabilities",Yb="io.modelcontextprotocol/clientInfo",eS="io.modelcontextprotocol/serverInfo",tS={name:"cursor",version:"1.0.0"},rS=new Map;function nS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oS(e){const t=new URL(String(e));return t.hash="",t.href}function sS(e,t){const r=rS.get(e);return!(void 0===r||r<=t()&&(rS.delete(e),1))}function iS(e,t){try{return oS(e)===t}catch{return!1}}function aS(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}function cS(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Jb),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=nS(o.params)?o.params:{},a=nS(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===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,[Xb]:Jb,[Qb]:n.capabilities,[Yb]:n.clientInfo}}});return{...e,headers:s,body:l}}function lS(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function uS(e,t){const r=oS(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...tS}},s=!1;const i=()=>s||sS(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,cS(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!aS(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!nS(n)||!nS(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Jb))return lS({id:t,error:{code:Zb,message:"Unsupported protocol version",data:{requested:Jb,supported:s??[]}}});const i=nS(o._meta)?o._meta:{},a=nS(i[eS])?i[eS]:{name:new URL(r).hostname,version:"unknown"};return lS({id:t,result:{protocolVersion:Kb.aE,capabilities:nS(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){rS.set(e,t()+6e5)}(r,n)),d}return e(i,cS(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!iS(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!nS(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()&&iS(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=nS(l.message.params)?l.message.params:{};o={capabilities:nS(e.capabilities)?e.capabilities:{},clientInfo:nS(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?sS(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||!aS(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(!nS(r)||!nS(r.error))return!1;const n=r.error;if(n.code!==Zb||!nS(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Jb)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function dS(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()===qv));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()!==qv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function hS(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(qv,i),r(n,{...o,headers:a,redirect:"manual"})}}class pS{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=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var fS=r("crypto");function mS(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function gS(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 wS(e,t){return gS(e,t)}function yS(e){if(e)return(0,fS.createHash)("sha256").update(e).digest("hex").slice(0,12)}function vS(e){if(e&&0!==e.length)return yS(JSON.stringify([...e].sort()))}function bS(e){return{clientIdHash:yS(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:vS(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function SS(e){return"object"==typeof e&&null!==e}function kS(e,t){let r=e;for(const e of t){if(!SS(r)||!(e in r))return;r=r[e]}return r}function _S(e,t){for(const r of t){const t=kS(e,r.split("."));if("string"==typeof t)return t}}function CS(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function ES(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 xS=e=>e;function PS(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?DS(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?DS(t(r)):void 0}}function IS(e){if(e&&"object"==typeof e)return SS(e)?e.cause:void 0}function RS(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const TS="[REDACTED]",AS=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function $S(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${TS}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${TS}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${TS}`)}function MS(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function DS(e,t){return MS($S(e),t?.maxLength)}function OS(e,t=xS){if("string"==typeof e)return MS($S(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")||AS.test(t)}(e)?TS:"string"==typeof r?$S(t(r)):r));if(!r)return;return MS(r)}catch{return}}function FS(e,t=xS){const r=IS(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=PS(r,t),i=PS(e,t)??s,a=_S(e,["code","cause.code"]),c=CS(e)??CS(r)??_S(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:DS(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=kS(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??ES(i)??ES(s),d=OS(kS(e,["response","body"])??kS(e,["body"])??kS(e,["data"])??kS(e,["cause","body"])??kS(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 mS({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:RS(e,t),sdkErrorKind:p})}const NS={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 jS(e){const t=e.message??NS[e.event],r={event:e.event,cursorMcp:{oauth:mS({...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 LS=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]))),US=4096;function BS(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function WS(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function HS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qS(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(HS(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function zS(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function GS(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function VS(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:GS(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:GS(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:GS(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:GS(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:GS(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:GS(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:GS(t.get("content-length"))}}function KS(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 JS(e){const{input:t,init:r}=e,n=gS(WS(t)),o=function(e,t){const r=new Headers(qS(BS(e)?e.headers:void 0));return new Headers(qS(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=zS(o),i=o.get("content-type"),a=yS(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return LS.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(BS(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:VS(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function ZS(e,t){const r=zS(e.headers),n=GS(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:yS(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:yS(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:XS(e.headers,"retry-after"),slackRateLimitType:XS(e.headers,"x-slack-ratelimit-type")}}function XS(e,t){return e.get(t)?.slice(0,64)??null}function QS(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 YS(e,t){const r=JS({input:e,init:t});if(void 0!==KS(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 ek=e=>e;async function tk(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function rk(e){if(!YS(e.input,e.init))return;const t=await tk(e.response,US,e.redact);if(void 0!==t)try{return OS(JSON.parse(t))}catch{return DS(t,{maxLength:US})}}async function nk(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 tk(t,US,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=gS(WS(e.input)).path)&&!0!==t?.endsWith("/mcp"))return DS(e.rawText,{maxLength:US});var t;try{const t=JSON.parse(e.rawText);return HS(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!HS(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?DS(r.message,{maxLength:US}):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 rk({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ok(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function sk(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=>sk(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,sk(n,t,r+1)])))}function ik(e,t){const r=e=>{const r=sk(e,t,0);return HS(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 ak(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:ik(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await nk({input:s,init:i,response:e,redact:n??ek});return!r&&e.ok||ok((()=>{!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=JS({input:t,init:r}),l=KS(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:ZS(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")&&!YS(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:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!SS(e))return;const t=SS(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}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await nk({input:s,init:i,response:t,redact:n??ek}):{};throw ok((()=>{!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=FS(n,e.redactLogText),u=JS({input:t,init:r}),d=KS(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?ZS(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:QS(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}Error,Error;const ck=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),lk=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),uk=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];function dk(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}}const hk=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],pk=[".exe",".cmd",".bat"],fk=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,mk=new Set(["py","pyw"]),gk=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),wk=new Set;function yk(e){return hk.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 vk(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of pk)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(fk.test(r)||mk.has(r)||"uvx"===r)return!0;if("uv"===r){const e=vk(t,gk);return"run"===e?.value||"tool"===e?.value&&"run"===vk(e.rest,gk)?.value}return"pipx"===r&&"run"===vk(t,wk)?.value}(n,o)?yk(i)||yk(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function Sk(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 kk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),_k=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Ck=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Ek=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),xk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");function Pk(e){return`${typeof e}:${String(e)}`}function Ik(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(Pk(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Pk(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=Pk(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 Rk(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,Xs.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Tk{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,Kb.vo)(e)&&(0,Kb.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Kb.wU)(e)||await this.inner.send(e,t)}}const Ak=Ln.object({tools:Ln.array(Ln.unknown()),nextCursor:Ln.unknown().optional()}),$k={typeFilled:0,toolDropped:0,outputStripped:0};function Mk(e){if(Lk(e))return"string"==typeof e.name?e.name:void 0}function Dk(e){return Ok(e.issues.filter((e=>"outputSchema"===e.path[0])))}function Ok(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function Fk(e){if(!Lk(e))return e;const t={...e};return delete t.outputSchema,t}function Nk(e){return Lk(e)&&!("type"in e)}function jk(e,t){return{...e,inputSchema:{type:"object",...t}}}function Lk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Uk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const Bk=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Uk.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,Xs.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 Wk{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>=Sb}append(e){const t=Sb-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}=bi(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:kb(t),...r}))}catch{}}const Jk=(0,P.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 Zk(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Xk=["authorization_code","refresh_token"],Qk=["code"];class Yk{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=ob(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(Gv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?sb:rb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled??(()=>!1),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,Xs.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=()=>!1){const n=eb(e);if(!0!==n?.pinsScopesOverConfiguredScopes){if(void 0!==t&&t.length>0)return t;const n=ib(e);return void 0!==n&&r(n.gate)?n.baseScopes:t}return void 0===n.scopesPinGate||r(n.scopesPinGate)?n.scopes??t:t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=eb(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 e_(e){const{serverName:t,config:n,tokenStorage:o}=e,{isScopeChallengeStepUpEnabled:s}=e,i=await xb(n.url,e.fetchImpl),a=gb({loopbackIpv4:i?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),c=function(e,t){const r=Cb(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:wb(t),grant_types:[...Xk],response_types:[...Qk],token_endpoint_auth_method:"none"}}(n.auth,a),l=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:c});return new Yk({identifier:t,redirectUrl:a,serverUrl:n.url,restMcpProviderMetadata:i,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:wb(a),token_endpoint_auth_method:"none",grant_types:[...Xk],response_types:[...Qk],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...void 0!==s&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Hb({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),isEnabled:async()=>s(),readScopesSupported:t=>async function(e){try{const{discoverOAuthProtectedResourceMetadata:t}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"));return(await t(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch)).scopes_supported}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:l,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:l?.client_id})})}const t_=new Set;let r_=!1;function n_(){for(const e of t_)try{process.kill(e,"SIGKILL")}catch{}}function o_(e,t){return uS(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function s_(e,t,r){const n=dS(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?hS((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class i_{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 pS,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}})();jS({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(){return new _k.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}},extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}},jsonSchemaValidator:Bk})}setupElicitationHandler(){this.client.setRequestHandler(Kb.$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){const d=new URL(t.url);o=o??hb;const h=await e_({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,isScopeChallengeStepUpEnabled:u}),p=h.tokens(),f=dS(t.url,n),m=f.headers,g=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),w=void 0!==f.cursorAuthHeaderValue&&void 0!==f.cursorAuthOrigin&&void 0!==g?hS((()=>f.cursorAuthHeaderValue),f.cursorAuthOrigin,g):g,y=e=>void 0===w||void 0===i?w:ak({fetch:w,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let v;const b=e=>{const r=h.scopeStepUp,n=e??g;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,kk.j2)(h,{serverUrl:d.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==w?{fetchFn:w}:{}});const r=h.lastRedirectUrl;v=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:Vb(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){Ib(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 Gb(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},S=i_.createClient(),k=e=>e instanceof kk.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&ck.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!lk.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&&uk.some((e=>e.test(n)))}(e)}(e),_=async t=>{if(!h.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!==v&&v.redirectUrl===h.lastRedirectUrl?v.resourceMetadataUrl:void 0;await(0,kk.j2)(h,{serverUrl:d.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==w?{fetchFn:w}:{}}),a&&jS({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...wS(d.toString()),...dk(h.tokens(),{expiresInIsFresh:!0})}})},C=r=>{const n=h.lastRedirectUrl?.toString?.()??"",o=new i_(e,S,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await _(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:h,authCodeExchange:_,sessionId:r,config:t});return o},E=async()=>{const r=new Ck.A(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(y("sse"))});try{return await S.connect(r),new i_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await r.close().catch((()=>{})),k(t))return a&&jS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(p?.refresh_token),...wS(d.toString()),...FS(t,i?.redactLogText)}}),C();throw t}};if("sse"===t.type)return E();const x=new xk.j(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(o_(y("streamableHttp"),d))});try{await S.connect(x);const r=function(e,t=Date.now){return sS(oS(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:Rk({url:t.url,headers:n,accessToken:h.tokens()?.access_token})}}(S,x);return new i_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,sessionId:x.sessionId,protocolVersion:x.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(k(t))return a&&jS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(p?.refresh_token),...wS(d.toString()),...FS(t,i?.redactLogText)}}),C(x.sessionId);if(function(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)}(t))return E();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=i_.createClient(),o=new xk.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new i_(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=hb,i,a,c,l,u){const d=new URL(t.url),h=await e_({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=s_(t.url,o,i),m=new xk.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ak({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=i_.createClient();return await g.connect(m),new i_(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=hb,i,a,c,l){const u=await e_({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(Rk({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=s_(t.url,o,i),p=new xk.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=i_.createClient();return await f.connect(new Tk(p,r.result)),new i_(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 xk.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{qk(s,(0,c.VI)(e.withName("McpSdkClient.fromCommand")),!1);const u=(l=o?.spawn,void 0!==l||"linux"!==process.platform?l:(e,t,r)=>(0,_l.D9)(kl.spawn,e,t,r)),d=r.args??[],h=new Ek.oQ({command:r.command,args:d,env:bk({command:r.command,args:d,env:n}),cwd:r.cwd,stderr:"pipe",...u&&{spawn:u}}),p=function(e){const t=new Wk;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>DS(t.text.replace(/\s+/g," ").trim(),{maxLength:Sb}),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)}))}}}(h.stderr),f=i_.createClient(),m=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let g;h.onclose=()=>{var e;void 0!==g&&(e=g,t_.delete(e))};const w=new AbortController,y=f.connect(h,{timeout:m,signal:w.signal});let v;g=h.pid??void 0,void 0!==g&&(i=g,t_.add(i),r_||(r_=!0,process.on("exit",n_)));const b=new Promise(((e,r)=>{v=setTimeout((()=>r(new Error(`MCP server connection timed out after ${m}ms: ${t}`))),m)}));try{await Promise.race([y,b])}catch(e){throw w.abort(),y.catch((()=>{})),await h.close().catch((()=>{})),await p.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Hk.set(r,t),r}(e,p.read())}finally{void 0!==v&&clearTimeout(v)}return new i_(t,f,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==g,serverSignals:Ik(h)})}catch(e){s.error=e,s.hasError=!0}finally{zk(s)}var i,a,l}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 xk.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,ir.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof ir.MU?{outcome:"timeout",durationMs:t}:e instanceof xk.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=qk(t,(0,c.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Zk(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()=>{const e=await Sk({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...$k}}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}},Ak),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(Lk(e)){const r=e.inputSchema;Nk(r)&&(t=jk(e,r),s++)}let n=Kb.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Kb.Dn.safeParse(Fk(t));o.success&&(a++,r(Mk(e),Dk(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Mk(e),Ok(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(c_.has(n))return c_.delete(n),c_.add(n),!1;if(c_.add(n),c_.size>256){const e=c_.keys().next().value;void 0!==e&&c_.delete(e)}return!0})(n,this.serverName,e??"")&&Gk.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+=t.typeFilled,l_(r.ctx,"type_filled",t.typeFilled),l_(r.ctx,"tool_dropped",t.toolDropped),l_(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:Dy(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:Dy(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){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,e,n),e instanceof kk.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const t=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(t,this.stateValue,"runtime_unauthorized",{...FS(e,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}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=Kb.O4.MethodNotFound;if(t instanceof Kb.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof kk.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Kb.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof xk.b||e instanceof Ck._){const t=e instanceof xk.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&&Gk.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=qk(s,(0,c.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",Zk(this.config));const l=this._callToolLock,u=this._callToolQueueDepth;let d;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{d=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=qk(e,(0,c.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",u);const r=performance.now();await l;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",u)}catch(t){e.error=t,e.hasError=!0}finally{zk(e)}}if("requires_authentication"===this.stateValue.kind)throw new kk.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const d=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=qk(n,(0,c.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const l=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===l.isError),Kk(e,this.config,{isError:!0===l.isError}),{content:l.content,isError:!0===l.isError,structuredContent:(i=l.structuredContent,Oy(i)),_meta:Hy(l._meta)}}catch(e){n.error=e,n.hasError=!0}finally{zk(n)}}catch(t){t instanceof Gb?(Kk(e,this.config,{error:t,httpStatus:t.decision.status}),function(e,t){try{Jk.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,t)):Kk(e,this.config,{error:t});const r=t instanceof Gb&&"offer"===t.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==d;if((t instanceof kk.D_||r)&&"ready"===this.stateValue.kind){const e=this.stateValue,n=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:n,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,r?"scope_step_up":"runtime_unauthorized",{...FS(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,l.then(d)}}catch(e){s.error=e,s.hasError=!0}finally{zk(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},Kb.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(qk(t,(0,c.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{zk(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(qk(t,(0,c.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 Sk({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{zk(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return qk(r,(0,c.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{zk(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return qk(t,(0,c.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await Sk({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{zk(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return qk(n,(0,c.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{zk(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 a_=(0,P.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),c_=new Set;function l_(e,t,r){if(0!==r)try{a_.increment(e,r,{outcome:t})}catch{}}class u_ 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 d_{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new Yt(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class h_{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new d_({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class p_{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=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{zk(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 f_{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=qk(t,(0,c.VI)(e.withName("McpManager.getToolSet")),!1),n=qk(t,m_(this.listingDeadlineAt),!1),o=await(0,ir.PH)(Object.entries(this.clients),(([e,t])=>n.within(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},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 d_(a)}catch(e){t.error=e,t.hasError=!0}finally{zk(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qk(t,(0,c.VI)(e.withName("McpManager.getInstructions")),!1),n=qk(t,m_(this.listingDeadlineAt),!1),o=await(0,ir.PH)(Object.entries(this.clients),(([e,t])=>n.within(t.getInstructions(r.ctx)).then((e=>e&&0!==e.trim().length?new ps.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{zk(t)}}}function m_(e){if(void 0===e)return{concurrency:4,within:e=>e,[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:e=>Promise.race([e,r]),[Symbol.dispose]:()=>clearTimeout(t)}}function g_(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 w_{constructor(e){this.options=e,jS({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:wS(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return jS({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...dk(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),jS({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...dk(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){jS({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){jS({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...FS(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return jS({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...bS(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),jS({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...bS(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(jS({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 y_{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 v_{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 b_=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},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 k_=(0,x.h)("DefinitionMcpLoader");function __(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 C_(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function E_(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function x_(e){return e?.length??0}function P_(e){if(void 0!==e)return(0,Xs.createHash)("sha256").update(pv(e)).digest("hex")}function I_(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?Ov(r):r)}async function R_(e,t,n,o,s={middlewares:[],configPath:""},i,a,l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=b_(u,(0,c.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);let f=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=b_(s,(0,c.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(E_);return await async function(e,t,n,o){const s=n.cwd?__({filePath:n.cwd}):void 0;let i,a;if(n.args&&n.args.length>0)i=__({filePath:n.command,baseDir:s}),a=n.args.map((e=>__({filePath:e,baseDir:s})));else{const e=(0,Fv.A)(n.command);i=__({filePath:e[0],baseDir:s}),a=e.slice(1).map((e=>__({filePath:e,baseDir:s})))}const c=n.env??{},{startupTimeoutSec:l}=n,u=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),d=(0,my.$H)(u);if(void 0!==d){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:h}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),p=s??process.cwd(),f=await n(d,p);k_.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=${x_(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${x_(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${x_(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${P_(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:x_(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:x_(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:x_(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:P_(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}));try{return await i_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c,{spawn:(e,t,r)=>h(e,t,r,f)})}catch(e){if(e instanceof o)throw new fv(t,e);throw e}}return!0===u?.enabled&&"no_sandbox"===u.mcpNetworkMode&&(!0===u.win32UserExtensionUnsandbox?k_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):k_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),i_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c)}(h,t,n,e)}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){const c=g_(e,k_),l=function(e,t,r){return{logger:{debug:(t,r)=>k_.debug(e,t,r),info:(t,r)=>k_.info(e,t,r),warn:(t,r)=>k_.warn(e,t,r),error:(t,r,n)=>k_.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:I_(r)}}(e,t,a),u=void 0!==s&&yv(r.url)?vv(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return i_.fromStreamableHttp(t,r,n,r.headers,o,u,l,c,void 0,void 0,i)}(h,t,n,o,e,d.find(C_),a,l.isLinkSharedPaymentTokenLogRedactionEnabled)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{S_(s)}};for(const e of d){const r=f;f=async(n,o)=>await e.load(n,t,o,h,r)}try{return await f(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=Hk.get(e);void 0!==r&&Hk.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=bv(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 A_{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{b_(r,(0,c.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,ir.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=I_(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Hk.get(e)}(r);k_.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 f_(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{S_(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(E_);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,pv(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(k_.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,ir.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{b_(n,(0,c.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{S_(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new y_(this.tokenStorage,n),s=g_(e,k_),i=new w_({inner:o,logger:s,redactLogText:I_(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new v_(i):i;return R_(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.isScopeChallengeStepUpEnabled,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){k_.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 by||e instanceof Sy||e instanceof ky||e instanceof $_}(r)}}class $_ 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 M_=[1e3,3e3];class D_{constructor(e){this.blockingService=e}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={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked)throw new $_(t,i.reason??"teamPolicy",i.message);for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),t}catch(e){if(e instanceof gv)throw new $_(t,"teamPolicy",e.message);const r=e instanceof wv?M_[n]:void 0;if(void 0===r)throw e;await(0,ir.cb)(r)}}}class O_ extends A_{constructor(e,t,r=[],n={}){super(new T_(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new O_(t,e,r)}}function F_(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 N_=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function j_(e){const t=N_.VE.safeParse(e);return t.success?t.data:void 0}function L_(e){const t=N_.H5.safeParse(e);return t.success?t.data:void 0}class U_{constructor(e){this.mcpAuthPath=e;const t=U_.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,U_.mcpAuthPromises.set(e,t),t.catch((()=>{U_.mcpAuthPromises.get(e)===t&&U_.mcpAuthPromises.delete(e)}))}U_.saveLocks.has(e)||U_.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,ti.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=j_(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?j_(n.tokens):void 0,clientInfo:"clientInfo"in n?L_(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=U_.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;U_.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.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,ti.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}U_.mcpAuthPromises=new Map,U_.saveLocks=new Map;const B_=Buffer.from([137,80,78,71,13,10,26,10]),W_=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),H_=e=>{if(e.lengthe.subarray(e.length-W_.length).equals(W_)||(e=>{let t=B_.length+25;for(;t+W_.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-W_.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+W_.length).equals(W_);t+=W_.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)}},q_=e=>1===e||e>=208&&e<=216,z_=e=>192===e||193===e||194===e,G_=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,V_=e=>0===e||e>=208&&e<=215,K_=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=H_(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(q_(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=K_(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(q_(r)){t+=2;continue}if(218===r||217===r||G_(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(z_(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),Z_=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),X_=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,B_.length).equals(B_)?"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},Y_={0:1,2:3,4:2,6:4},eC=({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}`)}}},tC=({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)},nC={0:1,2:3,3:1,4:2,6:4},oC=[1,2,4,8,16],sC=[[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]],iC=async e=>{const t=aC(e);if(void 0===t)return;const r=cC(t);let n=0;const o=sh.Readable.from(t.idat).pipe((0,ah.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`)},aC=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=nC[i[9]];if(void 0===e||!oC.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}},cC=({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?sC.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const lC=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},uC=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),dC=e=>{if(!uC(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)}}},hC=e=>lC().decode(e),pC=e=>lC().encode(e);async function fC(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);J_(e.data);return e.resizeWithoutBudget(e.data)}const mC=[{width:1280,height:800},{width:1456,height:840}],gC=1048576,wC=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function yC(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 vC=(e,t,r=1024)=>yC(e,t,r),bC=(e,t,r)=>{e.resize({w:t,h:r})},SC=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`)},kC=(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:SC(((e,t)=>{switch(t){case"png":return(e=>{let t,r=B_.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Z_(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))}};const _C=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return fC({data:e,budgetBytes:r,maxImageBytes:gC,fitImage:yC,resizeWithoutBudget:e=>_C(e,n)})}if(uC(e))return(async(e,t)=>{const r=dC(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:wC(e),mimeType:"image/webp"};const n=void 0!==r&&mC.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!vC(r.width,r.height,1280).needsResize)&&e.length<=gC)return{data:wC(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:wC(e),mimeType:"image/webp"};SC(r);const o=await hC(e),s=(await uw()).fromBitmap({data:Buffer.from(o.data),width:o.width,height:o.height});let{width:i,height:a,needsResize:c}=n?{width:s.bitmap.width,height:s.bitmap.height,needsResize:!1}:vC(s.bitmap.width,s.bitmap.height,1280);c&&bC(s,i,a);let l=await pC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});for(;l.length>gC&&i>8&&a>8;)i=Math.max(8,Math.round(.8*i)),a=Math.max(8,Math.round(.8*a)),bC(s,i,a),l=await pC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});return{data:wC(l),mimeType:"image/webp",reencoded:!0}})(e,t);const r=J_(e);if(void 0!==r&&e.length<=gC&&!vC(r.width,r.height).needsResize)return{data:wC(e),mimeType:r.mimeType};const n=Q_(e);void 0!==n&&kC(e,n),"png"===n&&await iC(e);const o=await uw(),s=void 0===r?void 0:vC(r.width,r.height),i="image/png"===r?.mimeType&&!0===s?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(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=Y_[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}})(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{})):void 0,a=void 0===i?await o.read(e):o.fromBitmap(i),c=(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"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=vC(a.width,a.height);if(void 0===i&&!h&&e.length<=gC&&l===c)return{data:wC(e),mimeType:c};let p=u,f=d;h&&bC(a,p,f);let m=await a.getBuffer(l);for(;m.length>gC&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),bC(a,p,f),m=await a.getBuffer(l);return{data:wC(m),mimeType:l,reencoded:!0}},CC=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Q_(t);let n;if(uC(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{kC(t,r);const e=await uw();n=async()=>("png"===r&&await iC(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}};function EC(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 xC(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=gi(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?.[Nv]}(e)&&(t[Nv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}var PC=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},IC=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 RC=(0,P.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),TC=(0,P.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),AC=(0,P.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),$C=(0,P.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),MC=(0,P.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"]}),DC=(0,P.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"]}),OC=(0,x.h)("McpFileSystemWriter"),FC="mcpFsStructuredLogOptIn";function NC(e,t){return t?.includeStructuredLogs?{...e??{},[FC]:!0}:e}const jC={debug(e,t,r,n){OC.debug(e,t,NC(r,n))},info(e,t,r,n){OC.info(e,t,NC(r,n))},warn(e,t,r,n){OC.warn(e,t,NC(r,n))},error(e,t,r,n,o){OC.error(e,t,r,NC(n,o))}},LC="mcps",UC="tools",BC="~staging",WC="~prev",HC="mcp_auth",qC="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.",zC="# >>> CURSOR MANAGED BLOCK >>>",GC="# <<< CURSOR MANAGED BLOCK <<<",VC=["# 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 KC(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function JC(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function ZC(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function XC(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 QC(e){if(Array.isArray(e))return e.map((e=>QC(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,QC(t)]));return Object.fromEntries(t)}return e}function YC(e){return JSON.stringify(QC(e))}function eE(e){const t=e.map((e=>({value:e,key:YC(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function tE(e){const t=eE(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=eE(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=eE(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return YC({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 rE{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=>{jC.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),jC.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=`${zC}\n${VC}\n${GC}\n`;let n;await(0,ti.mkdir)(e,{recursive:!0});try{n=await(0,ti.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==rl(e))throw e}if(void 0===n)return void await(0,ti.writeFile)(t,r);const o=n.indexOf(zC),i=n.indexOf(GC,o+30);if(-1===o||-1===i)await(0,ti.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,ti.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{jC.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,LC);try{const e=await(0,ti.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(BC))).map((e=>(0,ti.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==rl(e)&&jC.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:Gt(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Gt(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){jC.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,be.q6)();return e&&(t=t.with(x._O,e)),t}getLogContext(e){return e.with(x._O,this.ctx.get(x._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return ZC(this.mcpAuthCopyOverrides?.authToolDescription)??qC}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Bt(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return ZC(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=ZC(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:HC},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Bt(e)?this.getNeedsAuthStatusMessage(e):ZC(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){jC.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${nl(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(jC.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 KC(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||jC.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?KC(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?KC(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?KC(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:XC(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=dE(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,LC,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=dE(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,LC,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===HC))||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:HC,name:HC,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)?jC.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):jC.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===HC))){const t=e.tools.find((e=>e.toolName===HC));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??[])];jC.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=>(jC.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 jC.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${nl(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=>{jC.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):jC.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)),jC.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=dE(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{PC(r,(0,c.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Gt(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=>(jC.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(jC.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);jC.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){jC.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{IC(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,UC,`${JC(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{PC(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,LC);await(0,ti.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,tE(e))}catch(t){jC.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&jC.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,ti.stat)((0,s.join)(i,e.sanitizedId))}catch{jC.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??dE(e);r.has(n)?(jC.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(jC.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}const d=void 0===this.cachedServerData;if(d)try{const e=await(0,ti.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(BC)&&!e.endsWith(WC))));for(const r of e)if(r.endsWith(BC))await(0,ti.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else if(r.endsWith(WC)){const e=r.slice(0,-5);if(t.has(e))await(0,ti.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,ti.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,ti.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 u.add(e)}catch(e){jC.error(o,"Error clearing mcps directory",e)}const h=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));jC.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:h,unchangedServerCount:t.length-l.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:d,projectDirHash:(0,Xs.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const p=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,ti.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{}))}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{PC(n,(0,c.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,ti.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,UC);await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=JC(r.toolName),n=(0,s.join)(e,`${t}.json`),o=qt(r);await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=JC(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,ti.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=JC(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,ti.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,ti.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,ti.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,ti.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;PC(r,(0,c.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&&jC.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=JC(t.toolName),n=(0,s.join)(e.folderPath,UC,`${r}.json`);return new ps.E$({toolName:t.toolName,definitionPath:n,...xC(t.annotations)})}));return new ps.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 ps.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{IC(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&&jC.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){jC.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&jC.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){jC.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{PC(t,(0,c.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,LC),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=dE(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=JC(e.name);return new ps.E$({toolName:e.name,definitionPath:(0,s.join)(r,UC,`${t}.json`),...xC(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===HC))){const e=JC(HC);n.push(new ps.E$({toolName:HC,definitionPath:(0,s.join)(r,UC,`${e}.json`)}))}return new ps.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})})),l=a.reduce(((e,t)=>e+t.tools.length),0);return jC.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new ps.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{IC(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{jC.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,LC),i=new Set,a=new Map;for(const e of t){const t=dE(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,ti.readdir)(o),c=c.filter((e=>!e.endsWith(BC)&&!e.endsWith(WC)))}catch(e){if("ENOENT"!==rl(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++,RC.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),jC.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++,RC.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,UC);let h=0;try{h=(await(0,ti.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,RC.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),jC.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}))}TC.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),AC.gauge(e,i.size,this.getMetricTags({mcp_source:r})),$C.gauge(e,l.size,this.getMetricTags({mcp_source:r})),MC.gauge(e,d,this.getMetricTags({mcp_source:r})),DC.gauge(e,p,this.getMetricTags({mcp_source:r})),jC.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||jC.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())}}rE.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var nE=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},oE=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 sE(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 iE=(0,x.h)("local-exec:mcp");function aE(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function cE(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function lE(e){return new rr._Z({content:{case:"image",value:new rr.do({data:e.data,mimeType:e.mimeType})}})}function uE(e){return new rr._Z({content:{case:"text",value:new rr.zN({text:e})}})}function dE(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 hE(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client}});if(!n)return;const o=await fu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new rr.iz({result:{case:"error",value:new rr.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Ow.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 rr.iz({result:{case:"approved",value:new rr.Ke}}):null:new rr.iz({result:{case:"rejected",value:new rr.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new rr.iz({result:{case:"error",value:new rr.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class pE{constructor(e,t,r,n,o=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}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}}(Vt(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=nE(r,(0,c.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),l=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),u=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),d=a.find((e=>e.name===t.name));if(void 0!==d&&(void 0!==u?d!==u:d.toolName!==t.toolName||d.clientKey!==i&&d.providerIdentifier!==i))return new rr.iz({result:{case:"error",value:new rr.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const h=void 0===u?void 0:await this.toolSet.getClient(o,u.clientKey).catch((()=>{})),p=await hE(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u,...void 0===h?{}:{client:h}});if(void 0!==p)return p;const f=await this.toolSet.getToolSet(o);let m;try{m=await f.execute(u?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(er(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new u_(t.providerIdentifier,l)),r instanceof u_){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new rr.iz({result:{case:"error",value:new rr.Nh({error:e})}}):new rr.iz({result:{case:"serverNotFound",value:new rr.JL({name:r.serverName,availableServers:r.availableServers})}})}if(er(r))return new rr.iz({result:{case:"toolNotFound",value:new rr.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const g=[];for(const e of m.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)g.push(uE(e.text));else if("resource"===r){const r=By(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await _C(n).then(lE,(e=>{iE.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));g.push(s??uE(Wy(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 _C(s)}catch(e){iE.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)}),g.push(uE(`[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}g.push(lE(i))}else if("image"!==r){const t=Wy(e);g.push(uE(t))}}const w=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 rr._Z({content:{case:"text",value:new rr.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:g,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.join(t,ml),n=s.join(r,`${(0,Xs.randomUUID)()}.txt`);await(0,ti.mkdir)(s.dirname(n),{recursive:!0});const o=gi(e,gl),i=wa(o),a=Buffer.byteLength(o,"utf8");return await(0,ti.writeFile)(n,o,"utf8"),new bl.pV({filePath:n,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===w)throw new Error("Failed to materialize MCP text output");const y=m.structuredContent&&"object"==typeof m.structuredContent&&!Array.isArray(m.structuredContent)?ar.Struct.fromJson(m.structuredContent):void 0,v=new rr.QW({content:w,isError:m.isError,structuredContent:y,resultMeta:void 0===m._meta?void 0:ar.Struct.fromJson(m._meta)});return new rr.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{oE(r)}var n}}class fE{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=nE(r,(0,c.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 rr.kP({result:{case:"error",value:new rr.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new rr.kP({result:{case:"success",value:new rr.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 rr.kP({result:{case:"success",value:new rr.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new rr.kP({result:{case:"error",value:new rr.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{oE(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 rr.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:sE(e.annotations)}))):[]}}class mE{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Ot),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=nE(r,(0,c.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Ow.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ar.Value.fromJson(t.server),uri:ar.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ar.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new rr.ZD({result:{case:"rejected",value:new rr.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 rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new rr.ZD({result:{case:"error",value:new rr.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 rr.ZD({result:{case:"notFound",value:new rr.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,ti.realpath)(r),o=s.resolve(r,t.replace(/^\/+/,""));if(!aE(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.dirname(o);for(;;)try{if(!aE(n,await(0,ti.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==cE(e))throw e;const t=s.dirname(i);if(t===i)throw e;i=t}if(await(0,ti.mkdir)(s.dirname(o),{recursive:!0}),!aE(n,await(0,ti.realpath)(s.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,ti.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==cE(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,ti.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,ti.writeFile)(e,t)}return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:sE(r.annotations),metaJson:Ht(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new rr.ZD({result:{case:"success",value:new rr.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:sE(r.annotations),metaJson:Ht(r._meta),content:{case:"blob",value:e}})}})}return new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return iE.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new rr.ZD({result:{case:"error",value:new rr.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{oE(r)}}}async function gE(e,t){const r=dE(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,ti.readdir)(n)}catch(e){if("ENOENT"===rl(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,ti.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 wE=(0,x.h)("local-exec:mcp-disk-freshness-on-access"),yE="/mcps/",vE=(0,P.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),bE=(0,P.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),SE=(0,P.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),kE=(0,P.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),_E=new Map;function CE(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function EE({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 wE.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>dE(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void wE.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"};vE.increment(e,1,{...l,outcome:c}),bE.histogram(e,i.length,l),SE.histogram(e,a.length,l),kE.histogram(e,i.length+a.length,l),"mismatch"===c&&wE.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 xE(e,t,r,n=gE){if(void 0===r||(void 0===(o=r)||!CE(o).includes(yE)))return;var o;const s=function(e){const t=CE(e),r=t.indexOf(yE);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=_E.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{_E.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=dE(r.serverIdentifier);await EE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await EE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{wE.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);_E.set(i,d)}async function PE(e){try{return(await(0,ti.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function IE(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 RE(e,t,r=PE){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,ir.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof ir.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:IE(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}const TE=BigInt(0),AE=BigInt(8),$E=BigInt(16),ME=BigInt(65535);function DE(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function OE(e){const t=e.split(".");if(4!==t.length)return;let r=TE;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<>$E&ME)),t.push(Number(o.value&ME))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function NE(e){return OE(e)??function(e){const t=DE(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=FE(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<$E|BigInt(t)),TE)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=FE(n),i=FE(o);if(!s||!i)return;const a=s.length+i.length;return a>7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<<$E|BigInt(t)),TE)}}(e)}function jE(e,t){const r=DE(e),n=DE(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=NE(t.slice(0,r)),o=NE(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>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 LE(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=>jE(e,t)))}(r.hostname,t)}function UE(e){return e.trim().toLowerCase()}function BE(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function WE({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":UE(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(UE).filter((e=>e.length>0)),n=void 0===e?void 0:UE(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:BE(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}const HE=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function qE(e){return e.trim().split(/\s+/).filter(Boolean)}function zE(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 qE(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return HE.has(n)}function GE(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=GE(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(KE(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(KE(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(KE(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const ZE=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],XE=["cursor","molten glass"];function QE(e){return ZE.some((t=>e===t||e.startsWith(`${t}.`)))}const YE=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],ex=[{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"},...YE,{bundleId:ZE[0],name:"Cursor"}];function tx(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=ex.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}:QE(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>XE.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:ZE[0],name:"Cursor"}:void 0}const rx=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 nx(e){return rx.has(e.toLowerCase())}function ox(e){return`app/${e}`}function sx(e){return"object"==typeof e&&null!==e}function ix(e){return cx.includes(e)}function ax(e){if(!sx(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!sx(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!ix(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 cx=["pid","bundleId","path","appName"],lx=/^[+-]?\d+$/;var ux=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const dx="win32"===process.platform;function hx(e,t){return dx&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const px=(0,s.join)((0,o.homedir)(),".cursor","projects"),fx=(0,s.join)((0,o.homedir)(),".cursor","worktrees");function mx(e){return hx(px,e)&&e!==px}function gx(e){return hx(fx,e)&&e!==fx}function wx(e,t){const r=function(e){if(!hx(px,e))return;if(e===px)return;const t=(0,s.relative)(px,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function yx(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function vx(e){const t=rl(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:nl(e)}}}async function bx(e,t){const r=(0,ki.o1)(e,t);try{return yx(await(0,ti.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==rl(e))return yx(r,r,vx(e));try{if((await(0,ti.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,ti.readlink)(r)}catch{}return yx(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return yx(await(0,ti.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==rl(e))return yx(r,r,vx(e))}return yx(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===rl(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,ti.realpath)(t);return yx((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==rl(t))return yx(e,e,vx(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return yx(e,e,{status:"newFile"})}(r):yx(r,r,vx(e))}}}function Sx(e){return"resolved"===e.status||"newFile"===e.status}function kx(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 _x({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o}){return"workspace"===r.boundary&&!Cx(t,n)&&!Cx(t,o)&&!(xx(t,r.allowPaths)||e!==t&&xx(e,r.allowPaths))}function Cx(e,t){return t.some((t=>(0,ki.BJ)(e,t)))}function Ex(e){return e.flatMap((e=>{const t=(0,ki.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function xx(e,t){const r="win32"===process.platform?ki.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ki.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&ta(r(t),n)}))}const Px=/(?{const t=await bx(e);return Sx(t.resolution)?t.resolvedPath:(0,ki.o1)(e)})))}function Ux(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 Bx(e){return[...new Set(e)]}function Wx(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Hx({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 qx(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function zx(e){return"<"!==e.operator&&"<&"!==e.operator}function Gx(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Vx(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function Kx({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(Sx(a.resolution)){for(const e of r){const t=await o(e);if(Sx(t.resolution)&&Hx({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:s}))return"workspace-file"}return n&&oP(a.resolvedPath,i)?"tmp-file":void 0}}function Jx(e){return Bx(e.map((e=>e.trim())).filter(Boolean))}function Zx(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 Xx(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Qx(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Ir.r6({type:"word",value:e})));return new Ir.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Yx(e,t={}){return{type:e,...t}}function eP(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 tP(e,t){if("workspace"===e&&void 0!==t)return t}const rP={workspace:0,system:1};function nP(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 oP(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){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||!Hx({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 sP(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,oi.$b)(e.networkPolicy),n=(0,oi.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,oi._B)(e.networkPolicy),s=(0,oi._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!(rP[i]>rP[a])}class iP{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&sP(t,r);this.state=o?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!sP(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function aP(e){return e?.type??"undefined"}const cP=["skills","skills-cursor","rules","plugins"];async function lP(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function uP(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function dP({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 hP=/^\s*Read\s*\((.*)\)\s*$/,pP=/^\s*Write\s*\((.*)\)\s*$/;class fP{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.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy}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]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]):[[],[]],i=r.map((e=>this.compileReadDenyMatcher(e))),a=e=>i.some((t=>t(e)));return async(e,r)=>a(e)||a(r)||n&&_x({requestedAbsolutePath:e,realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s})}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:eP(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 Lx([...Ex(e),...(0,oi.r5)()])}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,Qs.r_)(e)))),...cP.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,oi.W1)(e)??[]));return Lx([...this.rootDirectories,...r,...n])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ki.o1)(e),o=await ll(n);if(null===o)return{type:"unsafeResolution",message:Ux("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(!mx(o)&&!gx(o)&&!t&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:o,requestedAbsolutePath:n});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const{perms:r,setting:n}=await this.readControlSetting();if("workspace"!==n.boundary||"unrestricted"===r.approvalMode)return!1;const o=await this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName);return!Cx(e,o)&&(!!_x({requestedAbsolutePath:t,realAbsolutePath:e,setting:n,resolvedWorkspaceRoots:o,resolvedAllowFolders:await this.resolvedReadAllowFolders(n.allowPaths)})&&{type:"needsApproval",approvalReason:n.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 shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Tx(n,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const a=await bx(t);if(!Sx(a.resolution))return{type:"unsafeResolution",message:kx(a.originalPath,a.resolution)};const l=a.resolvedPath,u=l;if(await this.ignoreService.isRepoBlocked(u))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",l))return{type:"permissionsConfig"};const d=a.originalPath.split(s.sep).pop()?.toLowerCase()??"",h=l.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===d||".cursorignore"===h)return{type:"permissionsConfig"};const p=mx(u),f=gx(u),m=!p&&!f&&await this.ignoreService.isCursorIgnored(u);if(p||f);else if(m)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",l))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(l))return!1;const g=await this.getPermissions();if("workspace_readonly"===g.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===g.approvalMode)return!1;for(const e of this.rootDirectories){const t=await bx(e);if(!Sx(t.resolution))continue;const r=t.resolvedPath;if((0,ki.BJ)(l,r)){const e=(0,s.relative)(r,l).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const w=async()=>{let e,t,n="";try{n=await ac(l),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,ux.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 y,v=!1;for(const e of this.rootDirectories){const t=await bx(e);if(!Sx(t.resolution))continue;const r=t.resolvedPath;if((0,ki.BJ)(l,r)){v=!0,y=r;break}}const b=v?void 0:function(e){if(!gx(e))return;const t=(0,s.relative)(fx,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(fx,t[0]):void 0}(l);if(!v&&void 0===b){if(function(e){return oP(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(l))return!1;if(wx(l,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(l.startsWith(e)){const e=l.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const S=y??b,k=l;let _=(0,s.relative)(S,k).split(s.sep);if(_=_.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&_.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${_[_.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,oi.OK)(l,S)){const e=_[_.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await w();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const C=await this.checkCursorFileProtection(_);if(C)return C;if(!0===g.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await w();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{Ax(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 ll(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Ux("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}}:{kind:"allow"}}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($x.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:aP(l),requestedPolicyType:aP(n),effectiveRequestedPolicyType:aP(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:qr(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 $x.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:aP(l),requestedPolicyType:aP(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.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,v="allowlist"===a&&i.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==v,S=v?v.map(Qx):d,k=void 0!==v?v.map(Zx):S.map((e=>[e.fullText.trim()].filter(Boolean))),_=void 0!==y?y.commands.map(Zx):k;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,oi.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,oi._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 C;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,oi.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,oi.wG)(tP(e.readBoundary,e.additionalReadPaths),tP(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),m&&$x.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});const E=[],x=[];let P=[],I=[],R=[];const T=Jx(i.smartAllowlistDenylist??[]);if(T.length>0){I=[];const t=_.map((e=>e[0]??""));for(let e=0;e<_.length;e++){const r=_[e];if(r&&0!==r.length&&T.some((e=>Xx(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&($x.info(e,"Command blocklist: commands require approval",{count:I.length}),E.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));$x.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const n=k.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(zE(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),Jx(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=JE(P,R),t=e.length>0?e.join(", "):P.join(", ");x.push(`Not in allowlist: ${t}`)}C=o&&0===I.length,C&&$x.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,$=S.map(((e,t)=>new iP(e,n,A,k[t])));if((0===S.length||f&&!b)&&!c){$x.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:aP(n),userConfiguredPolicyType:aP(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const o={type:Ow.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:w}};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{allRedirectsAreWorkspaceFileSafe: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 j=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:I});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return $x.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=qr(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&&Px.test(r)||Rx(r,Px,Ix)||Rx(r,/(?0&&(j.hasSecurityDenies||j.hasSoftDenies||!j.allCommandsRunnable);if(void 0!==g&&G.push(g),L&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),E.length>0&&(V||G.push(...E),z=!1),!V)if(b&&x.length>0)G.push(...x);else if(j.unapprovedCommands.length>0){const e=JE(this.generateAllowlistPatterns(j.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):j.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(j.hasSecurityDenies&&(V||(j.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),j.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${j.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=j.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");$x.info(e,"Shell permissions: commands not in team allowlist",{commandCount:j.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J=G.join(" • "),Z=[];if(z){const e=void 0!==g?$.filter((e=>"allowlisted"!==e.state)):j.unapprovedCommands;Z.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const X=b&&x.length>0,Q=X?P:Z,Y=X&&R.length>0?R:void 0,ee="insecure_none"!==n.type&&"insecure_none"!==l.type,te="insecure_none"!==n.type,re=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,E.length>0?"command_blocklist":void 0,b&&x.length>0?"smart_allowlist_miss":void 0,j.unapprovedCommands.length>0?"unapproved_commands":void 0,j.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));$x.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:aP(n),userConfiguredPolicyType:aP(l),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:z,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:re,commandCount:$.length,unapprovedCommandCount:j.unapprovedCommands.length,deniedCommandCount:j.deniedCommands.length,notInTeamAllowlistCount:j.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSecurityDenies:j.hasSecurityDenies,hasSoftDenies:j.hasSoftDenies});const ne={type:Ow.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&ee,isSandboxEnabled:"allowlist"===a&&te,canAllowlist:z,notAllowedCommands:Q,suggestedAllowlistEntries:Y,smartModeApprovalReason:g,smartModeApprovalRequestId:w}};r.onApprovalRequested?.();const oe=await this.pendingDecisionStore.requestApproval(ne);if(oe.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.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,d=l?c.commands.map(Qx):u;if(0===d.length)return!1;const h=l?c.commands.map(Zx):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Zx):h,f={type:"insecure_none"},m=d.map(((e,t)=>new iP(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=Jx(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>Xx(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const w=await this.teamSettingsService.getAutoRunControls();if(void 0!==w&&m.some((e=>this.isInTeamBlocklist(w,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:w,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const{userSandboxDataFolderName:t,teamAdminPolicy:r}=await this.getPermissions(),n=void 0!==t&&t.length>0?(0,s.join)((0,o.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,i=await this.foldPerUserFilePolicy(e,n),a=i.skipStatsigDefaults?i:await this.applyStatsigDefaults(i),c=await this.loadPerRepoFilePolicy(a.type);if("unavailable"===r){const{policy:e}=await(0,oi.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,oi.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const l=void 0===r?await this.buildTeamAdminPolicy(a.type):Yx(a.type,function(e){return"workspace"===e.readBoundary?e:void 0===e.networkPolicy?{}:{networkPolicy:e.networkPolicy}}(r)),u=(0,oi._B)(e.networkPolicy),{policy:d}=await(0,oi.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c,teamAdmin:l});return u?{...d,networkPolicy:(0,oi.T6)()}:d}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,oi.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,oi.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,oi.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};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,oi.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,oi._B)(e.networkPolicy))return e;const r={default:"deny",allow:Bx(t.allowlist)};return{...e,networkPolicy:(0,oi.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,oi.tv)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Yx(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await 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:Bx(i.allowlist)}:{},...i.denylist.length>0?{deny:Bx(i.denylist)}:{}}:void 0:(0,oi.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});return void 0===t?void 0:Yx(e,t)}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){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return 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=bx,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=Wx();for(const e of l){if(Vx(e))continue;const o=u?Wx():d,{operator:i,targetText:l}=e,p=e.destinationFds;if(">&"===i){const e=Gx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===i){const e=Gx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!qx(i)||void 0===l){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await Kx({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(zx))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c,redirectsAllowlistSafe:l}}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?{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=this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Ow.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",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}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ia({matchForms:t.parsingResult?ra({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?($x.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.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==nP(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=nP(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){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return 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 n of e)zE(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?hP:pP}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=ea(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,ki.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,ki.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 ta(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{Tx(o,(0,c.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:l}=t,u=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:EC(r.annotationsJson)}(t,r?.annotations),d=e=>{this.mcpAllowlistLog?.(e)};if(d(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return d(`[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 h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return d(`[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=dP({server:uP(a),tool:i});let b,S,k;switch(w.kind){case"block":return d(`[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 d(`[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 d(`[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?(d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(d(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:u}):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,...jx(r,u),providerIdentifier:a,args:l,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:u});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return d(`[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 d(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;d(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return d(`[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,...jx(r,u),providerIdentifier:a,args:l,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Ax(o)}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(uP(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=ax(e.meta?.["cursor/computerUseScope"])??ax(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])=>ix(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&&lx.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?tx(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&&lx.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:tx(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 QE(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":YE.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.":ex.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=nx(o.app.bundleId)?void 0:dP({server:r.serverId,tool:ox(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=uP(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(uP(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||nx(e)?void 0:dP({server:this.computerUse.serverId,tool:ox(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??EC(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=uP(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}){Mx.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&&jE(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&&function(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=UE(e);return 0!==r.length&&t.some((e=>UE(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}(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 mP=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 gP=65536,wP=1048576,yP=(0,x.h)("LocalReadExecutor"),vP=async(e,t,r,n)=>{const o=setTimeout((()=>{yP.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function bP(e){return BigInt(Math.min(e,4294967295))}async function SP(e,t){if(0===t)return(0,ti.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,ti.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function CP(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 EP=Buffer.from("\n---\n");function xP(e,t){const r=e.length;if(r<2*EP.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(EP,r-EP.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+EP.length,r-4).toString("utf-8"))?o:r}const PP=[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 IP(e){return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:e,reason:"File content is binary data, not text"})}})}function RP(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=TP(s,e),c=TP(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function TP(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 AP(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function $P(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 MP(e,t,r){const n=$P((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 DP(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=AP(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=gi(c,o)),{text:c,truncated:l}}function OP(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=AP(e.slice(t,o));const i=s.length>n||on&&(s=gi(s,n)),s.lengthn?{text:e.text+gi(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function NP(e,t){if(e.truncated)return e;const r=FP(e,t);return{text:r.text,truncated:r.truncated}}function jP(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=FP(n,"\n")),n=FP(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function LP(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 UP(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?tr:Math.min(tr,e.maxChars+2)}function BP(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 WP extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function HP(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return qP(r)>t?t:0}return 0}function qP(e){return e>=240?4:e>=224?3:e>=192?2:1}class zP{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 WP}validate(e){let t=e;if(this.carry.length>0){const r=qP(this.carry[0]??0)-this.carry.length;if(e.length0?Math.min(t,wP):wP,o=await SP(e,r);return o.length===t&&(0,n.isUtf8)(o)||Ta(new fa.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===wP&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function KP(e){const t=await(0,ti.stat)(e),r=await dc(e);if(r.isBinaryFile)return;const n=GP({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await VP(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function JP(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,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,j=0,L=!1,U=!1;const B=e=>{let t=e;return!L&&t.length>0&&(L=!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>=tr,q=()=>v||w&&g>=tr,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=tr-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:gi(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=tr-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:gi(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++:j++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.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===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t1&&A>tr;)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-HP(e));return Q=new zP(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 fa.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,ni.createReadStream)(t,{highWaterMark:gP,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 WP;throw e}return}const i=(0,ni.createReadStream)(t,{highWaterMark:gP,signal:e.signal,...s}).pipe(ma.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=NP(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&&Sc(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)+gP,ae=e=>e.text.length>ie?{text:gi(e.text,ie),truncated:!0}:e,ce=()=>jP({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(jP({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class ZP{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}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,c.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new nr.sV({result:{case:"error",value:new nr.F_({path:o,error:_i})}});const i=(0,ki.o1)(o,this.workspacePath),a=await vP(e,"permissionsService.shouldBlockFileRead",3e3,(()=>lP(this.permissionsService,i)));if(a){const r=await vP(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await fu(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:Ow.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 nr.sV({result:{case:"rejected",value:new nr.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new nr.sV({result:{case:"permissionDenied",value:new nr.lW({path:i})}})}void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,i);try{const r=await vP(e,"stat",3e3,(()=>(0,ti.stat)(i)));if(r.isDirectory())return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new nr.sV({result:{case:"invalidFile",value:new nr.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=or(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=or(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 vP(e,"getFormatForFile",3e3,(()=>dc(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=sc(i);if(l){const t=await vP(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await _C(e)}catch(t){const r=await CC(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await CC(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,ti.readFile)(i))));return"undecodable"===t.kind?new nr.sV({result:{case:"invalidFile",value:new nr.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 nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(u){const t=await vP(e,"readPdfBinary",3e3,(()=>(0,ti.readFile)(i)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await vP(e,"readBinaryFile",3e3,(()=>(0,ti.readFile)(i)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:bP(r.size),truncated:!1})}})}if(c.isBinaryFile)return IP(i);{const n=this.useStreamingRead,o=!n||await vP(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>tr){const n=await vP(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=GP(t,r.encodingHint);try{return await JP(e,t,r,o,n)}catch(o){if(o instanceof WP)return await JP(e,t,r,await VP(t.file,t.stats.size),n);throw o}}(e,{file:i,stats:r,format:c},t,o)));return new nr.sV({result:{case:"success",value:new nr.mE({path:i,output:{case:"content",value:BP(n.content,n.truncated,t)},totalLines:n.totalLines,fileSize:bP(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await vP(e,"readText",3e3,(()=>ac(i,t.encodingHint))),a=await vP(e,"countLines",3e3,(()=>wa(s))),l=function(e,t,r){const n=RP(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:MP(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=UP(t);return u.length>h&&(u=BP(u.substring(0,h),!0,t),d=!0),u.lengthSP(t,r.size)));if(o&&(i=s,PP.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return IP(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=kP(e),o=xP(e,n);if("utf-8"!==CP(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=$P((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=OP(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=kP(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=xP(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=$P((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=DP(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,UP(n));return new nr.sV({result:{case:"success",value:new nr.mE({path:t,output:{case:"content",value:BP(a.content,a.truncated,n)},totalLines:a.totalLines,fileSize:bP(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function XP(e){return Buffer.from(e,"utf16le").toString("utf16le")}var QP=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},YP=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 eI(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 tI(e){return`Path '${e}' is neither a file nor a directory`}async function rI(e){const t=await(0,ti.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function nI(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ki.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 oI extends Error{}function sI(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function iI(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 aI(e){switch(e){case"content":return new ay.vD({result:{case:"content",value:new ay.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new ay.vD({result:{case:"files",value:new ay.T7({ripgrepTruncated:!0})}});case"count":return new ay.vD({result:{case:"count",value:new ay.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function cI(e,t){let r=Buffer.concat(e);t&&(r=r.subarray(0,r.lastIndexOf(10)+1));const n=r.toString("utf8");return n.includes("�")?{stdout:n,stdoutBytes:r}:{stdout:n}}function lI(e){return/^(utf-?16|ucs-?2)/i.test(e)}const uI=(0,x.h)("local-exec/grep"),dI=(0,P.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"]}),hI=(0,P.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"]});function pI(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function fI(e){try{return(0,ni.existsSync)(e)}catch{return"check_failed"}}function mI(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function gI(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 wI(e,t,r,n){return{...vI(e),...n,cwd:t,cwdExists:fI(t),errorMessage:nl(r),errorCode:rl(r),errno:mI(r),syscall:gI(r,"syscall"),errorPath:gI(r,"path")}}function yI(e){return new Error(`Path does not exist: ${e}`)}function vI(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,ni.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,ni.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,ni.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,ni.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,ni.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,ni.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,ni.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 e=r.concat("node_modules.asar");try{t.asarExists=(0,ni.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,ni.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,ni.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class bI{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;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}computeRelativeTarget(e,t){const r=(0,ki.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,ki.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,ki.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ki.o1)(t.path,this.singleWorkspacePath??e);return(0,ki.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 Oc(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,ti.stat)(e)).isFile())return;const{encoding:t}=await dc(e);return lI(t)?t.toLowerCase():void 0}catch{return}}((0,ki.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,ki.o1)(s.file,t),i=await ll(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 RE(t,(e=>(0,ki.o1)(n(e),r)));return s.statTimedOut&&(uI.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),hI.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,bI.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const h=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),p=await this.buildArgs(t,r,"files_with_matches",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,i);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?bI.HARD_MAX_OUTPUT_LINES:bI.CLIENT_LIMIT_LINES,d=bI.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 cy;let s=0,i=0,a=0;for(;ly(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(l,u,d)),g=m.totalFiles>bI.CLIENT_LIMIT_LINES;let w=m.files;n&&(w=await this.keepNewestPage(h.ctx,w,t,(e=>e),i),g&&(w=w.join("\0").split("\0")));const y=(await this.filterBlockedFiles(w.map((e=>({file:e}))),t)).map((({file:e})=>e)),v=w.length-y.length,b=new ay.T7({files:y,totalFiles:py(m.totalFiles-v),clientTruncated:g,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new ay.vD({result:{case:"files",value:b}}),timedOut:f.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(a)}var l,u,d}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const h=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),p=await this.buildArgs(t,r,"count",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,i);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?bI.HARD_MAX_OUTPUT_LINES:bI.CLIENT_LIMIT_LINES,d=bI.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 cy;let i=0;for(;ly(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}}(l,u,d)),g=n?await this.keepNewestPage(h.ctx,m.counts,t,(e=>e.file),i):m.counts,w=await this.filterBlockedFiles(g,t),y=w.reduce(((e,t)=>e+t.count),0),v=g.length-w.length,b=g.reduce(((e,t)=>e+t.count),0)-y,S=new ay.xA({counts:w.map((e=>new ay.sS({file:e.file,count:py(e.count)}))),totalFiles:py(m.totalFiles-v),totalMatches:py(m.totalMatches-b),clientTruncated:m.totalFiles>bI.CLIENT_LIMIT_LINES,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new ay.vD({result:{case:"count",value:S}}),timedOut:f.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(a)}var l,u,d}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const l=QP(a,(0,c.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),u=await this.buildArgs(t,r,"content",n),d=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,h=bI.CLIENT_LIMIT_LINES*(d?2:1),p=await this.executeRg(l.ctx,t,u,h,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=await this.decodeLinesAsRead(l.ctx,p,t,i),{byFile:m,totalLines:g,totalMatchedLines:w,clientTruncated:y,ripgrepTruncated:v}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return QP(o,(0,c.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 cy;let a=0,c=0,l=0,u=0;for(;ly(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:py(l),totalMatchedLines:py(a),totalFiles:py(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{YP(o)}}(f,bI.CLIENT_LIMIT_LINES,h,l.ctx),b=Array.from(m.values()),S=await this.filterBlockedFiles(b,t),k=b.filter((e=>!S.includes(e))),_=k.reduce(((e,t)=>e+t.matches.length),0),C=k.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),E=n?await this.orderNewestFirst(l.ctx,S,t,(e=>e.file),i):S,x=new ay.Zp({matches:E.map((e=>new ay.uI({file:e.file,matches:e.matches.map((e=>new ay.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:py(g-_),totalMatchedLines:py(w-C),clientTruncated:y,ripgrepTruncated:v||p.timedOut||p.stdoutByteCapped});return{result:new ay.vD({result:{case:"content",value:x}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{YP(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=QP(s,(0,c.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),l=function(e,t){const r=[],o=new cy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&ly(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)))],d=new Map,h=performance.now()+bI.LINE_ENCODING_TIMEOUT_MS;let p=0;for(;p{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(bI.ripgrepTimeoutError());let f;try{const e=s;f=(0,oi.spawnInSandbox)((0,oi.Ko)(),r,{cwd:t},e),0}catch(r){if(p(),pI(r)){const n=(0,oi.Ko)();if(uI.error(e,"rg_diagnostics.spawn_throw",void 0,wI(n,t,r,i)),!1===fI(t))return u(yI(t))}return u(r)}const m=[],g=[];let w=0,y=0,v=0,b=!1,S=!1;const k=()=>{if(!d)try{p();const e=cI(m,!0);""===e.stdout?u(bI.ripgrepTimeoutError()):c({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:S}),f.kill()}catch{}};o.addEventListener("abort",k,{once:!0});const _=()=>{o.removeEventListener("abort",k),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",_,{once:!0}),f.stdout?.on("data",(e=>{if(!S&&!b)if(w+=e.length,w>l){S=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,b=!0;try{f.kill()}catch{}break}v+=r;const o=t>=0?e.subarray(0,t):e;m.push(o)}else m.push(e)})),f.stderr?.on("data",(e=>{y+=e.length,y<=l&&g.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_),p(),pI(r)){const n=(0,oi.Ko)();if(uI.error(e,"rg_diagnostics.spawn_enoent",void 0,wI(n,t,r,i)),!1===fI(t))return void u(yI(t))}u(r)})),f.on("close",(t=>{d=!0,o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_);const r=cI(m,S),n=Buffer.concat(g).toString("utf8");p(),c({...r,stderr:n,exitCode:t??0,timedOut:!1,stdoutByteCapped:S})}))}))}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 ll(t[0]);return null===r?{error:eI(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await rI(t[0])?{error:tI(e)}:{resolvedTarget:r}}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const i=QP(n,(0,c.VI)(e.withName("LocalGrepExecutor.execute")),!1),a=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(o=l)&&"files_with_matches"!==o&&"count"!==o)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:a},h=Ki(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(a);if((0,ki.fl)({targetPath:t.path,workspacePaths:a,mainWorktreePath:p?.mainWorktreePath}))return new ay.Ud({result:{case:"error",value:new ay.ts({error:ki.PS})}});const f=this.findOutsideTargets(t.path,a);let m=t,g=a;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new ay.Ud({result:{case:"error",value:new ay.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,r.resolvedTarget),g=a.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,a)){if(!(0,ki.BJ)(s,o))continue;const i=await ll(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await rI(s))return new ay.Ud({result:{case:"error",value:new ay.ts({error:tI(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&xE(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:eI(m.path);return new ay.Ud({result:{case:"error",value:new ay.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(i.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(i.ctx,d),t=e?sI(bI.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=aI(u),n++,o=!0;continue}if(!1===fI(s))return new ay.Ud({result:{case:"error",value:new ay.ts({error:`Path does not exist: ${s}`})}});const a=t??sI(bI.MAIN_TIMEOUT_MS);try{const t=await this.runMode(i.ctx,u,s,m,e,a.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof oI))throw t;if(r[s]=aI(u),n++,o=!0,!e)break}finally{a!==t&&a.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(iI));if(this.reportDeadlineReached(i.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw bI.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=>nI(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 ay.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 ay.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 ay.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),c=new ay._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ki.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new ay.Ud({result:{case:"success",value:c}})}catch(e){if(m.path){const e=(0,ki.o1)(m.path,this.singleWorkspacePath);try{await(0,ti.stat)(e)}catch(t){return new ay.Ud({result:{case:"error",value:new ay.ts({error:`Path does not exist: ${e}`})}})}}return new ay.Ud({result:{case:"error",value:new ay.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{YP(n)}var o}}bI.MAIN_TIMEOUT_MS=25e3,bI.INDEXED_GREP_TIMEOUT_MS=25e3,bI.INDEXED_GREP_CONTEXT_TIMEOUT_MS=bI.INDEXED_GREP_TIMEOUT_MS+100,bI.HARD_MAX_OUTPUT_LINES=1e4,bI.CLIENT_LIMIT_LINES=2e3,bI.LINE_ENCODING_TIMEOUT_MS=2e3,Ln.object({record_v:Ln.number().int().nullish(),pid:Ln.number().int().nonnegative().nullish(),version:Ln.string().nullish(),started_at:Ln.number().nullish(),control_sock:Ln.string().nullish(),runtime_dir:Ln.string().nullish(),data_dir:Ln.string().nullish(),config_path:Ln.string().nullish(),log_path:Ln.string().nullish(),metrics_addr:Ln.string().nullish(),exe:Ln.string().nullish()}),Ln.object({mountpoint:Ln.string().nullish(),capabilities:Ln.array(Ln.string()).nullish(),nfs_transport:Ln.string().nullish(),bind_ignored:Ln.object({active:Ln.array(Ln.string()).nullish()}).passthrough().nullish()}),Ln.object({daemon_alive:Ln.boolean().nullish(),mounts:Ln.array(Ln.unknown()).nullish(),data_plane:Ln.object({enabled:Ln.boolean().nullish()}).passthrough().nullish()});const SI=Ln.number().int().nonnegative(),kI=Ln.object({line_no:Ln.number().int().positive(),kind:Ln.enum(["match","before","after"]),text:Ln.string().optional(),bytes:Ln.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Ln.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Ln.object({type:Ln.literal("file"),path:Ln.string(),lines:Ln.array(kI)}),Ln.object({type:Ln.literal("summary"),files_searched:SI,more:Ln.boolean(),stop_reason:Ln.string().nullable(),skipped:Ln.object({over_size:SI,size_unknown:SI,budget_exhausted:SI,fetch_failed:SI,unreadable:SI})}),Ln.object({type:Ln.string()}),(0,x.h)("local-exec/grove-grep");var _I=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),CI=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},EI=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 xI{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{CI(r,(0,c.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ki.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,ti.stat)(n)}catch(e){return"ENOENT"===rl(e)?function(e){const t=or(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:"No active terminals."})}}):new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:`Path does not exist: ${n}`})}}):new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:nl(e)})}})}if(!r.isDirectory())return new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Ki(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 _I.fv({result:{case:"timeout",value:new _I.ze({directoryTreeRoot:a})}}):new _I.fv({result:{case:"success",value:new _I.PC({directoryTreeRoot:a})}})}catch(e){return new _I.fv({result:{case:"error",value:new _I.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{EI(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return CI(o,(0,c.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{EI(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{CI(i,(0,c.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),l=new _I.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(a,l);const d={charactersUsed:a.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=jc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,s.resolve)(t,e),n=await ll(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){i.error=e,i.hasError=!0}finally{EI(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 _I.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]=py(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=py(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 _I.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)}}var 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 II=1e4,RI=5e3,TI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class AI{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,tII&&(this.fullOutput="")}getOutput(){return this.totalChars<=II?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=II))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class $I{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Ei-this.kept.length;this.full=e.length>=t,this.kept+=gi(e,t)}get text(){return this.kept}}function MI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class DI{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 Ir.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new Ir.QR(o)};return new Ir.W4({result:i,sandboxPolicy:Ji(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,oi.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new AI,a=new $I,l=new $I;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,oi.ue)((0,oi.Xw)({...process.env,...TI,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,_l.D9)(kl.spawn,y.executable,y.args,w):(0,oi.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:fy(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=Ir.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=Ir.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:MI(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,c.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ki.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new Ir.W4({result:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Ir.W4({result:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:s,reason:mu(l.reason)})}});a=l.policy,Fi()&&(a=Wi(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:u,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{PI(r)}}}var OI=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function FI(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class NI{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:FI(t.cursor),advance:!1!==t.advance});return new OI.Ev({result:{case:"success",value:new OI.iS({events:e.events.map((e=>new OI.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 OI.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new OI.Ev({result:{case:"error",value:new OI.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class jI{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new xr.nt({result:{case:"error",value:new xr.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new xr.nt({result:{case:"success",value:new xr.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class LI{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,R.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 UI(e,t){return`${e}:${(0,Xs.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function BI(e,t){const r=new ri.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=UI(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 WI=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),HI=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class qI{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"),zI(GI(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),zI(new WI.GL({result:{case:"success",value:new WI.uX({path:t.path,diagnostics:e.map(VI)})}}),await o))}catch(e){return r("unavailable"),zI(GI(t.path,e instanceof Error?e.message:String(e)),await o)}}}function zI(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function GI(e,t){return new WI.GL({result:{case:"error",value:new WI.HW({path:e,error:t})}})}function VI(e){return new HI.oQ({severity:KI(e.severity),range:new bl.Q6({start:new bl.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new bl.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function KI(e){switch(e){case 1:return HI.h_.ERROR;case 2:return HI.h_.WARNING;case 3:return HI.h_.INFORMATION;case 4:return HI.h_.HINT;default:return HI.h_.UNSPECIFIED}}class JI{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 HI.Ek({result:{case:"success",value:new HI.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new HI.Ek({result:{case:"error",value:new HI.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new HI.Ek({result:{case:"error",value:new HI.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{ZI(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 HI.oQ({severity:this.convertSeverity(e.severity),range:e.range?new bl.Q6({start:new bl.yX({line:e.range.start.line,column:e.range.start.character}),end:new bl.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 HI.h_.ERROR;case 2:return HI.h_.WARNING;case 3:return HI.h_.INFORMATION;case 4:return HI.h_.HINT;default:return HI.h_.UNSPECIFIED}}}async function QI(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 ty().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 YI(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 YI(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 YI{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 eR=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]=nR(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=sR(e)}],[/^\+\+\+\s/,e=>{u(),n.to=sR(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},tR=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,rR=/^(a|b|i|w|c|o|1|2)\//,nR=e=>{const t=e?.match(tR);return t?.map((e=>e.replace(rR,"").replace(/("|')$/,"")))},oR=/^\\?['"]|\\?['"]$/g,sR=e=>{let t=iR(e,"-+").trim();return t=cR(t),t.replace(oR,"").replace(rR,"")},iR=(e,t)=>{if(e=uR(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=lR(t);return e.replace(new RegExp(`^${r}+`),"")},aR=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,cR=e=>{const t=aR.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},lR=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${uR(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,uR=e=>`${e??""}`,dR=(0,x.h)("local-mercurial-diff"),hR=5242880,pR="0000000000000000000000000000000000000000";let fR,mR;async function gR(e,t,r={}){const n=await async function(){if(void 0===fR&&(fR=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 ti.stat(t)).isFile())continue;return"win32"!==process.platform&&await ti.access(t,ni.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===fR){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return fR}();return await new Promise(((o,s)=>{const i=(0,kl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new Ic.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"}`))}}))}))}async function wR(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await ti.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!==mR)return mR;const e=await ti.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await gR(e,["help","environment"]);mR=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){mR=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await ti.rm(e,{recursive:!0,force:!0})}return mR}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await gR(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await ti.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function yR(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function vR(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 bR(e){const t=s.resolve(e);try{return await ti.realpath(t)}catch{return t}}function SR(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 kR(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function _R({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await gR(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>hR?"":gR(e,["cat","-r",t,"--",r])}async function CR(e,t,r){const n=function(e){switch(e){case jn.ek.NAME_STATUS:return jn.ek.NAME_STATUS;case jn.ek.NAME_STATUS_AND_NUMSTAT:return jn.ek.NAME_STATUS_AND_NUMSTAT;case jn.ek.FILE_DIFFS:return jn.ek.FILE_DIFFS;case jn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return jn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return jn.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await gR(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){kR(t),r.push("log");const n=(await gR(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===pR)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await gR(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==pR)return n;const o=(await gR(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==pR)return o;const s=(await gR(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:pR}({cwd:t,baseRef:r.baseRef,commands:o});else if(kR(r.baseRef),o.push("log"),a=(await gR(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(kR(r.ref),o.push("log"),c=(await gR(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 gR(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new jn.o$({diffs:eR(t).map((e=>function(e){const t=new jn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new jn.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:jn.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 gR(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 ti.stat(r);if(n.size>hR){const t=await async function(e){const t=(0,Xs.createHash)("sha256"),r=await ti.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 ti.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 jn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=SR(e.contents);if(0===t.length)return new jn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new jn.QP({from:"/dev/null",to:e.path,chunks:[new jn.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!==jn.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===jn.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 _R({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 ti.stat(e);t.afterFileContents=r.size>hR?"":await ti.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await _R({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=SR(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,Xs.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 gR(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:pR,g=(await gR(t,["status","-0"])).length>0}dR.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new jn.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 dR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return dR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const ER=(0,x.h)("local-git-diff");function xR({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function PR(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 xR(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function IR(e){const t=eR(e);return new jn.o$({diffs:t.map((e=>function(e){const t=new jn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new jn.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:jn.Wf.UNSPECIFIED})}function RR(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:wa(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 TR=["main","master","develop"];async function AR(e,t){const r=s.join(e,t),n=await ti.lstat(r);if(n.isSymbolicLink())return{contents:await ti.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await ti.readFile(r,"utf8"),path:t,isSymlink:!1}}async function $R(e,t,r){const n=ty(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await PR(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 bR(t);let n=await bR(e);if(yR(n,r))return;let o=!1;for(;vR(n,r)&&!yR(n,r);){try{if((await ti.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?wR(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await wR(e)?"none":"mercurial"}(t,o);if(ER.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw ER.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return CR(e,t,r);const a=function(e){switch(e){case jn.ek.NAME_STATUS:return jn.ek.NAME_STATUS;case jn.ek.NAME_STATUS_AND_NUMSTAT:return jn.ek.NAME_STATUS_AND_NUMSTAT;case jn.ek.FILE_DIFFS:return jn.ek.FILE_DIFFS;case jn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return jn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return jn.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await PR(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of TR){const r=`origin/${t}`;try{return await PR(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await PR(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await PR(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 PR(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=IR(h);else{const t=xR(d);if(r.computePatchId||!await async function(e){return(await PR(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 PR(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),ER.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 PR(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 AR(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${RR([e])}\n\\ No newline at end of file`:await PR(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...IR(t).diffs)}}if(a!==jn.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===jn.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 PR(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 PR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await AR(t,s.to)).contents}catch{try{s.afterFileContents=await PR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){ER.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 QI({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 PR(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){ER.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,RR(f))):void 0,v=!0===r.returnHeadSha?(await PR(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await PR(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new jn.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 MR{async execute(e,t){return $R(e,t.cwd,t)}}var DR=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class OR{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 DR.M({allowlisted:r})}}var FR=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),NR=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 jR(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function LR(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function UR(e){return e instanceof Error?e.message:String(e)}function BR(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: ${UR(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const WR=(0,fa.promisify)(kl.execFile);class HR{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(!jR(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,ir.wj)(Promise.all(e),HR.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 ti.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 ti.mkdir(this.stagingDir,{recursive:!0}),await ti.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:FR.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:FR.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:FR.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 ti.rename(e,t)}catch(e){if(!LR(e,"EXDEV"))throw e}try{await ti.copyFile(e,t)}catch(e){throw await ti.rm(t,{force:!0}).catch((()=>{})),e}try{await ti.unlink(e)}catch(e){throw await ti.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 ti.open(e,"wx");return await t.close(),e}catch(e){if(!LR(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,_l.D9)(WR,"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,_l.D9)(WR,"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:HR.PROXY_TARGET_FPS,includeBrandTag:!0}),await ti.access(n,ti.constants.R_OK)}catch(t){const r=(0,c.fU)(e);throw r?.setAttribute("error.type",function(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}(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,_l.D9)(WR,"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 ${HR.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${HR.PROXY_TARGET_FPS}fps`)}return HR.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await ti.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await jg(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${HR.DEFAULT_REFRESH_RATE}Hz`),o=HR.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${HR.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${HR.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",HR.PROXY_PRESET,"-crf",String(HR.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,_l.D9)(kl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.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);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.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);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.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:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,_l.D9)(kl.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 ti.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(jR(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{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),LR(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();try{const o=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!jR(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${UR(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await ti.access(d,ti.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=LR(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${UR(e)}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:BR(t,r,a,n)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=UR(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:BR(o,r,a,n)})}})}const m={profileVersion:HR.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:HR.PROXY_TARGET_FPS,codec:"h264",profile:HR.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:o,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await ti.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await ti.rm(g,{force:!0}).catch((()=>{})),e}try{await ti.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${UR(e)}`)}return this.clearActiveRecordingIfCurrent(r),new FR.Tj({result:{case:"saveSuccess",value:new FR.ol({path:g,recordingDurationMs:ar.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new FR.Tj({result:{case:"failure",value:new FR.yH({error:UR(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,c.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`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===FR.$u.UNSPECIFIED)return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case FR.$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 ti.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await ti.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await jg(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,o);r=a;const l=function(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}(this.display);n=new Vg({displayNum:l,resolution:i}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new FR.Tj({result:{case:"startSuccess",value:new FR.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await ti.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new FR.Tj({result:{case:"failure",value:new FR.yH({error:e instanceof Error?e.message:String(e)})}})}}case FR.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new FR.Tj({result:{case:"failure",value:new FR.yH({error:"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 FR.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new FR.Tj({result:{case:"failure",value:new FR.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!jR(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await ti.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new FR.Tj({result:{case:"discardSuccess",value:new FR.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await ti.rm(r,{force:!0,recursive:!0}),n=!0}catch{}this.activeRecording=null;const o=t instanceof Error?t.message:String(t),s=n?"":`. Session may remain at: ${r}`;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new FR.Tj({result:{case:"failure",value:new FR.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{NR(r)}}}async function qR(e){const t=await(0,ti.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 qR(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 zR(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(...zR(t,e,s))}))}return n}async function GR(e){if(!await(0,ti.access)(e,ti.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await qR(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>zR(e,"",r===t.length-1))).join("\n")}async function VR(e,t){return GR(s.join(e,"agent-notes",t))}async function KR(e){return GR(s.join(e,"agent-notes","shared"))}HR.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,HR.PROXY_TARGET_WIDTH=1920,HR.PROXY_TARGET_FPS=60,HR.PROXY_CRF=17,HR.PROXY_PRESET="veryfast",HR.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",HR.DEFAULT_REFRESH_RATE=60;var JR=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},ZR=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 XR=(0,x.h)("local-exec:request-context"),QR=Symbol("sectionLoadTimedOut");async function YR(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{JR(o,(0,c.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{ZR(o)}}async function eT(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 tT(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,oi.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,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Lr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ar.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 rT={type:"object",properties:{},additionalProperties:!1};function nT(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Wt.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new ps.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?ar.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oT(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 ps.E$({toolName:e.toolName,...xC(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?ar.Value.fromJson(e.inputSchema):void 0}}})));return!Bt(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===HC))||o.push(new ps.E$({toolName:HC,...r?{}:{description:qC,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rT)}:{inputSchema:ar.Value.fromJson(rT)}}})),new ps.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 ps.U_({enabled:!0,mcpDescriptors:n})}function sT(e){const t=e?.trim();return t||void 0}function iT(e,t){const r=function(e){return sT(e.serverIdentifier)}(e);if(r)return r;const n=sT(e.serverName);return n?t.get(n)??n:void 0}class aT{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(XR.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(XR.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=>iT(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=>iT(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=>(XR.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:Vt(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cT(e){return new rr._W({result:{case:"success",value:new rr.pv({servers:e.servers.map((e=>new rr.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new ps.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ar.Value.fromJson(e.inputSchema):void 0,metaJson:Ht(e._meta),...xC(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lT{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==rr.ew.FORCE_IF_MISSING&&t.refreshPolicy!==rr.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 cT({...r,servers:n})}return cT(r)}}class uT{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.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:I,isAttributionDisabledByAdmin:R,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=I,this.isAttributionDisabledByAdmin=R,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.onRequestContext=c.onRequestContext,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),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)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,be.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=JR(r,(0,c.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Jc(n.ctx,this.gitExecutor,t),s=o?await Zc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?Xc(s):void 0};this.cachedWorkspaces.set(t,i)}catch(e){r.error=e,r.hasError=!0}finally{ZR(r)}}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,be.q6)(),r=JR(e,(0,c.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)&&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{ZR(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=JR(t,(0,c.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,l,u,d]=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([]))]),h=Math.round(performance.now()-o);return h>1e3&&XR.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{ZR(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=JR(r,(0,c.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;const a=(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 Lr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Vc(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:c,branchName:l}=await async function(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(YR(e,t,r,n)),o(eT(e,t,r,n))]);return{status:s,branchName:i}}(n.ctx,t.gitExecutor,r.repoPath,3e3);return void 0===c&&(i=!1),new Lr.DS({path:r.repoPath,status:c,branchName:l,remoteUrl:r.remoteUrl,isOriginBacked:Vc(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:a,gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{ZR(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=JR(n,(0,c.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=JR(e,(0,c.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath){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{ZR(e)}},a=performance.now(),l={},u=(e,t)=>{const r=performance.now();return t.finally((()=>{l[e]=Math.round(performance.now()-r)}))},d=e=>function(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(QR)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}(e,this.sectionLoadTimeoutMs),h=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),[p,f,m,{gitRepos:g,gitRepoInfoComplete:w,gitStatusInfoComplete:y},v,b,S,k,_,C]=await Promise.all([u("globalCache",d(i())),u("mcpState",d(h((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(o.ctx))))),u("env",tT(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})),u("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),u("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?VR(s,t.notesSessionId):Promise.resolve(void 0)),u("sharedNotes",this.agentNotesEnabled&&s?KR(s):Promise.resolve(void 0)),u("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),u("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),u("agentSkills",d(h((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([]))))),u("adminCommandDenylist",d(h((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))]),E=p===QR,x=f===QR,P=_===QR,I=C===QR,R=E?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:p,T=x?{servers:[]}:f,A=P?[]:_,$=I?void 0:C;(E||x||P||I)&&XR.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:E,mcpState:x,agentSkills:P,adminCommandDenylist:I});const M=performance.now()-a;for(const[e,t]of Object.entries(l))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(M)),M>1e3&&XR.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(M),...l});const D=this.mcpMetaToolEnabled?oT(T,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,O=this.attributionConfigProvider?.get(),F=!k&&(O?.attribution?.attributeCommitsToAgent??!0),N=!k&&(O?.attribution?.attributePRsToAgent??!0),j=new Lr.bb({rules:R.rules,env:m,gitRepos:g,gitRepoInfoComplete:w,repositoryInfo:R.codebaseReference?[{relativeWorkspacePath:R.codebaseReference.relativeWorkspacePath,repoName:R.codebaseReference.repoName,repoOwner:R.codebaseReference.repoOwner,isTracked:R.codebaseReference.isTracked,isLocal:R.codebaseReference.isLocal,orthogonalTransformSeed:R.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:R.codebaseReference.pathEncryptionKey}]:[],...nT(T,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:v,sharedNotesListing:b,customSubagents:R.customSubagents,mcpFileSystemOptions:S,mcpMetaToolOptions:D,supportsMcpAuth:!0,commitAttributionMessage:F?"enabled":void 0,prAttributionMessage:N?"enabled":void 0,agentSkills:A,adminCommandDenylist:$?.rules??[]});return null!==R.cloudRule&&void 0!==R.cloudRule&&(j.cloudRule=R.cloudRule),this.reportSectionCompleteness&&(j.rulesInfoComplete=!E,j.customSubagentsInfoComplete=!E,j.agentSkillsInfoComplete=!P,j.mcpInfoComplete=!x,j.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==S,j.envInfoComplete=!0,j.gitStatusInfoComplete=y),j}catch(e){n.error=e,n.hasError=!0}finally{ZR(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=JR(r,(0,c.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 Lr._G({result:{case:"success",value:new Lr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(nl(e)),new Lr._G({result:{case:"error",value:new Lr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{ZR(r)}}}function dT(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Ir._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hT=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 pT{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Ir.W4({result:{case:"success",value:new Ir.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Ji(e.sandboxPolicy)}):new Ir.W4({result:{case:"failure",value:new Ir.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Ji(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?{perRepo: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?Ir.Lv.TIMEOUT:Ir.Lv.USER_ABORT:Ir.Lv.UNSPECIFIED:void 0,u=fy(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 Ir.W4({result:{case:"timeout",value:new Ir.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:Ji(o)}):e.signal.aborted?new Ir.W4({result:{case:"rejected",value:new Ir.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Ji(o)}):new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:Ji(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,c.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,c.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dT(t),l=(0,ki.o1)(i);if(!t.parsingResult)return new Ir.W4({result:{case:"spawnError",value:new Ir.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(zr(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId},s);if("block"===e.kind)return new Ir.W4({result:gu(o,l,e.reason)});u=s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Hr(t)},s);if("block"===e.kind)return new Ir.W4({result:gu(o,l,e.reason)});u=e.policy}if(Fi()&&(u=Wi(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await ul(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,i,a,u)}catch(e){r.error=e,r.hasError=!0}finally{hT(r)}}}var fT=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mT{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Ir.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fT.e({allowlisted:n})}}class gT{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Ir.jK({status:Ir.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wT=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 yT=(0,x.h)("local-exec:shell-stream");class vT{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===Ir.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:Ir.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:Ir.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 bT(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class ST{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}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,be.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new Ir.jK({status:Ir.iA.ACCEPTED,shellResult:o}):new Ir.jK({status:Ir.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(Ar).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:bT()},""!==e.toolCallId&&e.timeoutBehavior===Ir._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,c.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?Ki(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dT(t),l=(0,ki.o1)(i),u=Date.now(),d=new Ir.HO(di(o).structured),h=ca({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new Ir.FI({event:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:mu(p.reason)})}}));if(yT.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}),zr(t))yT.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"});else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:l,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Hr(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bT()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yT.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 Ir.FI({event:{case:"permissionDenied",value:new Ir.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=mu(n.reason);return void(yield new Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:o,workingDirectory:l,reason:r})}}))}s=n.policy,yT.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}if(Fi()&&(s=Wi(o,d)),s&&"insecure_none"!==s.type){const e=await ul(this.ignoreService);s={...s,ignoreMapping:e}}yield new Ir.FI({event:{case:"start",value:new Ir.tD({sandboxPolicy:Ji(s)})}});const f=t.timeoutBehavior===Ir._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?{perRepo: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 vT(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new Ir.W4({result:{case:"success",value:new Ir.QR({shellId:E,pid:C,command:o,workingDirectory:l,msToWait:fy(Date.now()-u),backgroundReason:Ir.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&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 D=k?.iterate()??b;try{for await(const r of D)if("stdout"===r.type)x+=r.data,yield new Ir.FI({event:{case:"stdout",value:new Ir.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new Ir.FI({event:{case:"stderr",value:new Ir.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;I=!0,r.aborted&&(n=e.signal?.aborted?Ir.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?Ir.Lv.TIMEOUT:Ir.Lv.USER_ABORT),yield new Ir.FI({event:{case:"exit",value:new Ir.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:fy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof oi.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yT.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new Ir.FI({event:{case:"sandboxUnsupported",value:new Ir.rI({command:o,workingDirectory:l,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||I||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===Ir.Jg.USER_REQUEST?Ir.Jg.USER_REQUEST:Ir.Jg.TIMEOUT,s=n===Ir.Jg.USER_REQUEST?Date.now()-u:a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:l,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new Ir.FI({event:{case:"backgrounded",value:new Ir.Y9({shellId:r,command:o,workingDirectory:l,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new Ir.FI({event:{case:"exit",value:new Ir.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:Ir.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wT(n)}}}const kT={kind:"absent"};class _T{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 ri.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(RT(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=RT(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=RT(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=RT(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=RT(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=RT(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}async function CT(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IT(t);const r=await xT(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}class ET{constructor(e,t,r,n){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n}async execute(e,t,r){const n=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ki.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===n)return this.inner.execute(e,t,r);const o=this.reads.begin(n);try{let s,i;try{s=await lP(this.permissionsService,n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}if(!1!==s&&"needsApproval"!==s.type)return await this.readAndForget(e,t,r,n,o);if(!1!==s){const s=await this.inner.execute(e,t,r),i=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await xT(t)}catch{return}}(s,n.resolvedPath);return this.commit(n,o,s,i),s}try{i=await xT(n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}const a=await this.inner.execute(e,t,r);return this.commit(n,o,a,i),a}finally{this.reads.end(n,o)}}commit(e,t,r,n){"fileNotFound"!==r.result.case?void 0===n||"success"!==r.result.case||"content"!==r.result.value.output.case?this.reads.forget(e,t):this.reads.record(e,{kind:"fingerprint",...n},t):this.reads.record(e,kT,t)}async readAndForget(e,t,r,n,o){const s=await this.inner.execute(e,t,r);return this.reads.forget(n,o),s}}async function xT(e){try{const t=await(0,ti.stat)(e);if(!t.isFile()||t.size>tr)return}catch(e){return TT(e)}let t;try{t=await(0,ti.open)(e,function(){const e=ni.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>tr)return;const n=(0,Xs.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=tr;){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>tr)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return TT(e)}finally{await(t?.close())}}function PT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}async function IT(e){try{return await(0,ti.stat)(e),!0}catch(e){if(AT(e))return!1;throw e}}function RT({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function TT(e){if(!AT(e))throw e}function AT(e){const t=rl(e);return"ENOENT"===t||"ENOTDIR"===t}var $T=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class MT{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new $T.M({allowlisted:r})}}var DT=r("node:constants");class OT extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}const FT=new fa.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),NT=new Map([["€",128],["‚",130],["ƒ",131],["„",132],["…",133],["†",134],["‡",135],["ˆ",136],["‰",137],["Š",138],["‹",139],["Œ",140],["Ž",142],["‘",145],["’",146],["“",147],["”",148],["•",149],["–",150],["—",151],["˜",152],["™",153],["š",154],["›",155],["œ",156],["ž",158],["Ÿ",159]]),jT=new Set([194,195,226,239]),LT=/\p{Lu}/u,UT=new Set([" ","­","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),BT=new Set(["¿","¡"]),WT=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,BT],[209,BT],[211,BT],[218,BT],[220,BT]]),HT=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),qT=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function zT(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:NT.get(e)}function GT(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&<.test(e[t-1]))return}else{if(UT.has(s))return;if(!0===WT.get(r)?.has(s))return;if(3===n&&HT.has(s)&&UT.has(e[t+2]))return}let i;try{i=FT.decode(o)}catch{return}return qT.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function VT(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=GT(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const KT=["mojibake","replacement_chars"];function JT(e){return e<=1?"1":e<6?"2-5":"6+"}function ZT(e){return e<=0?"0":JT(e)}function XT(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=nA(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function QT(e,t){return e<=t?"existing_only":"new_damage"}function YT(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(VT(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return VT(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 eA(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function tA(e,t,r){const n=VT(r,1e3);if(0===n.length)return eA("mojibake");const o=void 0===e?[]:VT(e,Math.max(n.length,6));return{detector:"mojibake",outcome:QT(n.length,o.length),file:XT(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:YT(n,o)}}function rA(e,t,r){const n=Aa(r);if(0===n)return eA("replacement_chars");const o=void 0===e?0:Aa(e);return{detector:"replacement_chars",outcome:QT(n,o),file:XT(e,o,t),afterCount:n,beforeCount:o}}function nA(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 oA=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 sA(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":oA.get(t)??"other"}const iA=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function aA(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:iA.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function cA(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:sA(t.path),encoding:nA(t.encoding),code_page:aA(t.pages),run_count:JT(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":ZT(n)),before_count:ZT(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}var lA=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 uA=(0,x.h)("LocalWriteExecutor"),dA=(0,P.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"]}),hA=async(e,t,r,n)=>{const o=setTimeout((()=>{uA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function pA(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function fA(e){try{return(await(0,ti.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===rl(e))return"missing";throw e}}async function mA(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await fA(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,ti.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 pA(e)}class gA{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,onWriteForAiTracking:i,writeFileMutationGuard:a,toolCallReads:c}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.onWriteForAiTracking=i,this.writeFileMutationGuard=a,this.toolCallReads=c}async execute(e,t){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Hp.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const r=(0,ki.o1)(t.path,this.workspacePath),n=this.toolCallReads,o=void 0!==n&&""!==t.toolCallId?n.take({toolCallId:t.toolCallId,resolvedPath:r}):void 0,s={writeStarted:!1},i=()=>{void 0===o||s.writeStarted||n?.restore(o)};try{const n=await this.executeWithRecord(e,t,r,o?.recorded,s);return vA(n)&&i(),n}catch(e){throw i(),e}}async executeWithRecord(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{const a=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}(i,(0,c.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=wx(r,["assets","agent-tools","swarm-agents"]);if((0,ki.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:ki.PS})}});let h,p,f=!1;try{if((await(0,ti.stat)(r)).size<=xi){const e=await hA(a,"readText before write",3e3,(()=>cc(r,t.encodingHint)));h=e.text,p=e.encoding}else f=!0}catch{}const m=(await bx(r)).resolvedPath,g=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await hA(a,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(a,m,l)));if(g){const e=await hA(a,"handleBlockReason",3e3,(()=>fu(g,{onNeedsApproval:async(e,o)=>{const s="fileEdit"!==o?.type||o.isNewFile,i="fileEdit"===o?.type?o.diffString:l,a="fileEdit"===o?.type?o.blockReason:void 0;if(await CT(n,m))return wA(r);const c=await this.pendingDecisionProvider.requestApproval({type:Ow.Write,details:{path:r,reason:e,isNewFile:s,diffString:i,before:h,after:l,blockReason:a},toolCallId:t.toolCallId});return c.approved?null:new Rr.v3({result:{case:"rejected",value:new Rr.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new Rr.v3({result:{case:"rejected",value:new Rr.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const w=await hA(a,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,ti.stat)(e)).isFile())return;const n=await(0,ti.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!==w)return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:w})}});const y=(0,s.dirname)(m);if(await async function(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IT(t)}catch{return!1}}(n,y))return wA(r);try{await hA(a,"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=await mA(e,t),i=0;for(;ir)throw pA(e);try{await(0,ti.mkdir)(a,{recursive:!1})}catch(r){const n=rl(r);if("EEXIST"===n){if("directory"!==await fA(a))throw r;i+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(a);if(n===a||"missing"!==await fA(n))throw r;o=await mA(e,t),i=0;continue}throw r}i+=1}}(y)))}catch(e){const t=rl(e);return"EACCES"===t||"EPERM"===t?new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:y,operation:"create_directory",error:"Permission denied"})}}):new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:nl(e)})}})}let v,b,S;if(void 0!==u)v=u,b=0;else{const e=await hA(a,"getBufferForWrite",3e3,(()=>uc(r,l,this.workspacePath,t.encodingHint)));v=e.buffer,b=e.lines,S=e.format.encoding}const k=()=>hA(a,"writeFile",3e3,(async()=>{if(await CT(n,m))throw new Error(PT(r));let e;a.signal.throwIfAborted(),o.writeStarted=!0,await async function(e,t,r){let n;try{n=await(0,ti.open)(e,function(){const e=ni.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=rl(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof ni.constants.O_NOFOLLOW}(t))throw new OT(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,ni.realpathSync)(e)}catch{throw new OT(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new OT(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new OT(e,`Refusing to write to non-regular file at ${e}`);await n.truncate(0);const s=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i{try{await k()}catch(e){throw _=e,C=!0,e}};try{void 0===this.writeFileMutationGuard?await k():await this.writeFileMutationGuard.runExclusive(m,E)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!C||e!==_))return new Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof OT)return new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=rl(e);return"EACCES"===t||"EPERM"===t?new Rr.v3({result:{case:"permissionDenied",value:new Rr.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===rl(e)?new Rr.v3({result:{case:"noSpace",value:new Rr.bM({path:r})}}):"EDQUOT"===t?new Rr.v3({result:{case:"error",value:new Rr.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 Rr.v3({result:{case:"error",value:new Rr.QM({path:r,error:nl(e)})}})}if(this.fileChangeTracker&&void 0===u&&!d&&!f){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(r,h,l,e)}if(this.onWriteForAiTracking&&void 0===u&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:h,afterContent:l,metadata:e})}catch(e){uA.warn(a,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const x=v.byteLength;let P;if(void 0!==u||f||d||this.recordEncodingChecks(a,r,h,p,l),t.returnFileContentAfterWrite)try{P=await hA(a,"readText after write",3e3,(()=>ac(r,t.encodingHint)))}catch{}return new Rr.v3({result:{case:"success",value:new Rr.j6({path:r,linesCreated:b,fileSize:x,...void 0!==P&&{fileContentAfterWrite:P}})}})}catch(e){i.error=e,i.hasError=!0}finally{lA(i)}}recordEncodingChecks(e,t,r,n,o){try{const s={path:t,encoding:n,pages:Dl.pages()};for(const t of function(e,t,r){return[tA(e,t,r),rA(e,t,r)]}(r,n,o))dA.increment(e,1,cA(t,s))}catch(t){for(const t of KT)dA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});uA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}}}function wA(e){return new Rr.v3({result:{case:"error",value:new Rr.QM({path:e,error:PT(e)})}})}class yA extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function vA(e){return"error"===e.result.case&&e.result.value.error===PT(e.result.value.path)}const bA=(0,x.h)("local-exec:provider"),SA=new Set,kA=new wl.AsyncLocalStorage;class _A extends ne{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of SA)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of SA)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,ni.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,oi.$6)(n);return(0,oi.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.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,oi.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});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 du(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,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new pu(c,this.askpassConfig)),this.shellManager&&(c=new hu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pT(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(Tr,BI(l)),this.register(Er,BI(new DI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _T,d=e.overrideWriteExecutor??new gA(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u});this.register($r,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(vA(e))throw new yA(e);return e}))},BI(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof yA)return e.result;throw e}}}}(d));const h=e.overrideDeleteExecutor??new Nw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking);this.register(ye,BI(h)),this.register(Se,BI(new Ww)),this.register(ke,new MR);const p=this.mcpStateAccessor??new aT(this.mcpLease),f=e.overrideGrepExecutor??new bI(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:p,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep});this.register(_e,BI(f));const m=e.overrideReadExecutor??new ET(new ZP(this.permissionsService,a,{mcpStateAccessor:p,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),u,this.permissionsService,a),g=new ur(m);this.register(dr,g),e.registerRedactedReadExecutor&&this.register(hr,g);const w=e.overrideLsExecutor??new xI(this.permissionsService,this.ignoreService,a);this.register(Ft,BI(w)),this.register(ve,BI(new XI(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(ge,BI(new qI(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Kt,BI(new Cr(new pE(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(dr))))),this.register(Jt,BI(new fE(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Zt,BI(new mE(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(Xt,BI(new lT(p,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const y=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(p,t,e),v=BI({execute:(e,t,r)=>{const n=kA.getStore();return void 0!==n&&(n.ran=!0),y.execute(e,t,r)}});this.register(jr,{execute:async(t,r,n)=>{const o={ran:!1},s=await kA.run(o,(()=>v.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 p.getState(t),l=nT(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oT(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=[],bA.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new $u(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(de,BI(this.backgroundShellExecutor)),this.shellStreamExecutor=new ST(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(Ar,function(e,t){const r=new ri.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=UI(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new LI(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor)),void 0!==e.agentStoreConflictDrainer&&this.register(le,new NI(e.agentStoreConflictDrainer)),this.register(Ur,new mT(this.permissionsService)),this.register(Qt,new OR(this.permissionsService)),this.register(En,new MT(this.permissionsService));const b=new gT(this.shellStreamExecutor);this.register(Br,BI(b));const S=!1===e.enableWriteBackgroundShellStdin?new jI((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new jI(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(he,BI(S)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(we,BI(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new HR({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Nr,BI(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uT(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,ki.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,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,onRequestContext:r.onRequestContext});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,SA.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}getRecordScreenExecutor(){return this.recordScreenExecutor}withPendingShells(e){return new oe(e,[te(Ar,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.rebuildRequestContextOnRulesChange&&(SA.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 CA(e){return e.replace(/\\/g,"/")}function EA(e,t){for(const r of t){const t=CA(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var xA;function PA(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return xA.Plugin;const n=CA(e.fullPath);return EA(n,r.builtinDirs)?xA.Builtin:Wm(e.fullPath,t).inAgentStore?xA.UserStore:EA(n,r.userDirs)?xA.UserHome:(EA(n,r.workspaceDirs),xA.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"}(xA||(xA={}));var IA=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 RA=(0,fa.debuglog)("merged-agent-skills"),TA=(0,x.h)("merged-agent-skills");class AA{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,c.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(RA("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 TA.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()]),l=i.flat(),u=this.getPromptSortContext?.(),d=qm(l,u??Um);let h=d;return a.ok?a.paths.length>0&&(h=d.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)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes($A));var t})),void 0!==u?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[km(e.userHomeDirectory).dirPath],r=Rm(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 Im(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:PA(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(h,u):h}catch(e){t.error=e,t.hasError=!0}finally{IA(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()}),AA.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()}}AA.CHANGE_COALESCE_MS=1500;const $A=`/${wm.configDir}/${wm.subdir}/`,MA=(0,x.h)("skill-sync-manifest"),DA=".sync-manifest.json";async function OA(e,t){try{const r=await(0,ti.readFile)((0,s.join)(e,DA),"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:(MA.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===rl(r)||MA.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function FA(e,t,r){e.skills[t]={lastSyncedAt:r}}function NA(e,t){delete e.skills[t]}var jA=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 LA=(0,x.h)("builtin-skills-sync");function UA(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function BA(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 WA(e){const t=Gp(e.content),r=UA(t.data)?t.data:{};return Vp(`${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={...UA(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 HA(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 qA(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,ti.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,ti.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,ti.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,ti.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,ti.writeFile)(t,r,"utf-8")}try{await(0,ti.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==rl(e))throw e}try{await(0,ti.rename)(n,r)}catch(e){throw i&&(await(0,ti.rename)(o,r),i=!1),e}i&&(await(0,ti.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,ti.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,ti.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===rl(t)||LA.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,ti.mkdir)(n,{recursive:!0}),await(0,ti.writeFile)(o,i,"utf-8"),!0}async function qA(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,ti.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===rl(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await qA(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function zA(e,t){try{return(await(0,ti.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===rl(r)||LA.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function GA(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,c.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),l=t.skillDir??km((0,o.homedir)()).dirPath;await(0,ti.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([OA(l,i),zA(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([VA((0,s.join)(r,"SKILL.md")),"canvas"===e?VA((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}})));LA.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){LA.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):LA.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:(t.canvasKit,Cm((0,o.homedir)()).dirPath),m=void 0!==f&&await VA((0,s.join)(f,_m)),g=new Set([...p.keys(),...d,...m?[_m]:[]]),w=e=>void 0!==f&&e===_m?f:l,y=e=>void 0!==f&&e===_m?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&&Wd(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)BA(t),f!==l&&await(0,ti.mkdir)(f,{recursive:!0}),await HA(i,f,{id:e,fileContent:WA(t),resources:t.resources??{}})?v++:b++,FA(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,ti.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),NA(u,e),h&&(S.push(e),LA.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||FA(u,e,a)}catch(t){LA.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),n=(0,s.join)(e,DA);await(0,ti.mkdir)(e,{recursive:!0}),await(0,ti.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,ti.rename)(r,n)}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===rl(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?LA.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):LA.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{jA(r)}var n}async function VA(e){try{return await(0,ti.stat)(e),!0}catch(e){const t=rl(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const KA=(0,x.h)("managed-skills-sync");function JA(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 ZA{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(...oh(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=JA(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var XA=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 QA(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class YA{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??Mu,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: ${nl(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: ${nl(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(Kf));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Kf(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=QA(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 Gf({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${nl(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,ti.realpath)(r);if(!(await(0,ti.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,ti.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 Wf(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}: ${nl(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,be.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,c.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=QA(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,l=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??i.length>0;if(!a&&!u&&!l)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 d=(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??Mu,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(zf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>Gf({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Mu,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,ti.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,ti.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,ti.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{ip(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,ti.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 Wf(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,ti.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=Vf(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=>Vf(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:l,loadCursorFirstParty:u&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:d}))):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: ${nl(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{XA(e)}}}var e$=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function t$(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function r$({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||LE(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class n${constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new e$.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new e$.aYW({}))}}function o$(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 s${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 i${constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new s$((()=>this.fetchSettings())),this.hostMcpBridgeClients=new WeakSet,this.teamRepos=new s$((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new s$((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){const e=this.settingsGeneration;try{const t=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e>=this.lastFetchedGeneration&&(this.lastFetchedSettings=t,this.lastFetchedGeneration=e),t}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){return this.settings.get().catch((()=>{}))}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(n){if(function(e,t){return!yy(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,my.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=r$({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?r$({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}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,my._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=t$(t.url);return void 0!==n&&r.some((e=>t$(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}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=WE({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===e$.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===e$.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===e$._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===e$.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:o$(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 a$=new sy,c$={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Jc((0,be.q6)(),a$,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?ei(r):void 0),workspaceRoots:n,createdAt:new Date}}},l$=(0,x.h)("ControlledConversationActionManager");class u${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,R.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 Gr.QFf({action:{case:"cancelAction",value:new Gr.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 R.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 R.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 R.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 R.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,R.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Gr.QFf({action:{case:"userMessageAction",value:new Gr.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){l$.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof R.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 R.W2("ControlledConversationActionManager disposed")))}}var d$=r("../cursor-sdk-local-runtime/dist/utils/logger.js");const h$="x-blob-encryption-key";function p$(e,t){const r={...t};return void 0!==r[h$]||(0,$n.TU)(e)&&(r[h$]=e),r}const f$=new Map;function m$(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function g$(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 w$(e){return new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:e})})}})}function y$(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function v$(e){e?.catch((e=>{d$.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const b$=new Set(["mcp.slack.com","setup.shopify.com"]);async function S$(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!==(i=e,a=r.restMcpHost,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?zv(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!b$.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await xb(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===Cb(t.CLIENT_ID)?{...c,...t,CLIENT_ID:c.CLIENT_ID}:{...c,...t}:c:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}class k${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 S$(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class _${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 C${constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class E${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 ky(t,n.configPath??"another config")}return await o(e,r)}}class x${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={};for(let e=0;e({prefix:t,scope:r,fileSource:new T_(e,"enterprise"===r||"env"===r?cv:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new _$(t,l),p=new C$(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,lv.indexOf(t)0?[new E$(f)]:[]],g=new A_(u?new k$(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new x$(y)}static init(e,t,r,n=!1,o,i={}){const a=new U_(s.join(r,"mcp-auth.json"));(async function(e){await(0,ti.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new Ey(s.join(r,"mcp-approvals.json"),t);return new P$(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 I$="cursor-plugins/local";function R$(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===I$)return r}class T$ extends p_{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class A${constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,ti.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,ti.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,ti.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class $${constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return d$.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&N$(r))continue;const e=F_(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}}):d$.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 M${constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:F$(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function D$(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};return{async createLease(a){const c=a.workspaceState,l=c.projectRoot??c.workingDirectory,u=c.projectDirectory;if(!l||!u)return new h_;const d=new A$((0,s.join)(u,"mcp-disabled.json")),h=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return P$.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new U_((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new Ey((0,s.join)(n,"mcp-approvals.json"),r),p=[new Iy,new Cy(h),new D_(t),new _y(a)],f=[];return c&&f.push({prefix:"",loader:new O_((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new O_((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),O$(f)}({teamSettingsService:t,projectRoot:l,projectDirectory:u,ignoreApprovals:r,disabledStore:d,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),p=[],f=e.inlineMcpServers??{};if(Object.keys(f).length>0){const e=new U_((0,s.join)(u,"mcp-auth.json")),r=[new Iy,new D_(t)];p.push({prefix:"",loader:new A_(new M$(f),e,r,i)})}const m=R$(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new Ey((0,s.join)(u,"mcp-approvals.json"),l),o=new U_((0,s.join)(u,"mcp-auth.json")),a=[new Iy];r||a.push(new Cy(e)),a.push(new D_(t),new _y(d));const c=new ZA(m.pluginsService),h=new A_(new $$(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new h_;const g=O$(p),w=await g.load(e.initializationCtx??(0,be.q6)(),e.cache);return new T$(w)}}}function O$(e){return 1===e.length?e[0].loader:new x$(e)}function F$(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 N$(e){return"claude-plugin"===e.pluginSource}function j$(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function L$(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class U${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>U$.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===$r.symbol||e===ye.symbol?{kind:"path"}:e===Tr.symbol||e===Ar.symbol||e===de.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=L$(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===Ar.symbol&&j$(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new Ir.FI({event:{case:"hookContext",value:new Ir.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===$r.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=L$(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,ir.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 B$(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}U$.CARRIERS_BY_EXEC_ID_MAX=32,Error,kl.execFileSync,new Map,ni.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 W$=["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(B$);function H$(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(q$,"\n\n"):r).trim()}(e,W$)}["system_reminder","system-reminder"].map(B$);const q$=/\n{3,}/g;function z$(e){const t=(0,Qs.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,Qs.sh)(e.parentConversationId);return`${Qs.O2}/${r}/subagents/${t}.${e.ext}`}return`${Qs.O2}/${t}/${t}.${e.ext}`}function G$(e){const t=(0,Qs.sh)(e.conversationId);return`${Qs.O2}/${t}.${e.ext}`}function V$(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(z$({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(z$({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(G$({conversationId:e.conversationId,ext:n}));return n}var K$;(()=>{const e=globalThis.Intl?.Segmenter;e&&new e(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(K$||(K$={}));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},Z$=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 X$(e){switch(e){case Gr.xyI.AGENT:return"agent";case Gr.xyI.ASK:return"ask";case Gr.xyI.PLAN:return"plan";case Gr.xyI.DEBUG:return"debug";case Gr.xyI.TRIAGE:return"triage";case Gr.xyI.MULTITASK:return"multitask";case Gr.xyI.CUSTOM:return"custom";case Gr.xyI.UNSPECIFIED:default:return"agent"}}function Q$(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 Y$(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 eM=new TextEncoder,tM=new TextDecoder,rM=new class{serialize(e){const t=JSON.stringify(e,Q$);return eM.encode(t)}deserialize(e){const t=tM.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Y$):JSON.parse(t)}};function nM(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function oM(e){return"system"!==e.role&&!nM(e)}function sM(e,t){return"user"===e.role&&"user"===t.role}async function iM(e,t,r){const n=await t.getBlob(e,r);return n?Gr.Anz.fromBinary(n).summarizedMessages:[]}async function aM(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=rM.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 cM(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 aM(e,t,o,n);r&&n.messages.push(r)}return n}async function lM(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=aM(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 dM(e){return H$(e)}const hM=/[\s\S]*?<\/think>/gi,pM=/[\s\S]*?<\/thinking>/gi,fM=/\n{3,}/g;function mM(e){let t=e;return t.includes("<")&&(t=t.replace(hM,"").replace(pM,"")),(t.includes("\n\n\n")?t.replace(fM,"\n\n"):t).trim()}function gM(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?dM(e):e;return r?mM(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=mM(t?dM(e.text):e.text);return uM({...e,text:r},!1)}return uM(e,t)})).filter(Boolean).join("\n")}function wM(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?dM(n):n,s="assistant"===e.role?mM(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?dM(r.text):r.text,s="assistant"===e.role?mM(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 yM(e){return e.endsWith("\n")?e:`${e}\n`}function vM(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 bM(e){if("system"===e.role||nM(e))return;const t=wM(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 SM{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=z$({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=J$(o,(0,c.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=vM(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:l,writeText:u,writeJson:d}=this.options;if(i&&a&&l&&!u&&!d&&!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 h=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=J$(n,(0,c.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,c.OA)(o.ctx),a=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await iM(i,t,e);return s+=r.length,await cM(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of g)a.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=J$(n,(0,c.VI)(e.withName("hydratePromptMessages")),!1),y=await cM(i,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const v=y.messages.filter(oM);return a.push(...v),a}catch(e){n.error=e,n.hasError=!0}finally{Z$(n)}}(s.ctx,this.blobStore,t);if(0===h.length&&0===o.jsonlLines.length)return!0;let p;if((this.options.writeText||e)&&(p=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=gM(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(h)),this.options.writeText){const e=p??"",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=wM(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(h);if(e||o.jsonlLines.length>0){const n={mode:X$(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&&sM(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=bM(e);t&&r.push(t)}return r.join("\n")}(h);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&p?.trim())try{const t=(await e(p)).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"),yM(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{Z$(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const l=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},u=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await l())};let d,h=0;const p=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 iM(e,t,s)}catch{continue}await lM(e,t,r,o,{skipFailedReads:!0,visit:n})}return await lM(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{oM(e)&&await n(e)}}),o}((0,c.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(h++,1!==h?(2===h&&d&&(sM(d,e)||await u(bM(d)),d=void 0),await u(bM(e))):d=e)}));d&&await u(bM(d));for(const e of t.terminalLines)await u(e);await l(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",p.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",p.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",p.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",p.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",p.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",p.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",p.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=vM(o),l=a.jsonlLines.length>0;if(i===n&&!l&&!o.overviewFactory)return i;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||l))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const d=J$(s,(0,c.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&l)try{return await u(this.resolveFilePath(r,"jsonl"),yM(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 cM(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=bM(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=yM(s.join("\n"));await u(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{Z$(s)}}}function kM(e){return Object.values(Ce).some((t=>t===e))}function _M(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 CM(e){return Je(e)?`prompt:${e.prompt}`:`command:${e.command}`}function EM(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class xM{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(CM(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=CM(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(!Me(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Me(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Ee&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Me(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=Le(r,this.logger),o=_t(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=_t(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,...EM(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))kM(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))kM(e)&&t.add(e);return t}}const PM="Read",IM="Write",RM="Delete",TM="List",AM="Grep",$M="Shell",MM="ReadLints";function DM(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const OM=new Set([PM,IM,RM,TM,AM,MM]);function FM(e){const t=DM(e,"tool_name"),r=[DM(e,"file_path"),"string"==typeof t&&OM.has(t)?DM(DM(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const NM=(0,x.h)("cli-hooks-executor");function jM(e){try{return(0,ni.statSync)(e).isFile()}catch{return!1}}const LM="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function UM(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function BM(e,t){const r=UM(e,t);if("string"==typeof r||null===r)return r}class WM{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,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,ih.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,Qs.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=V$(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,ti.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,Qs.Rv)((0,o.homedir)(),this.workspacePath),n=V$({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,ti.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,...EM(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?qe(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?qe(n,t):n).some((e=>Ze(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=UM(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 et.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Ce.subagentStop){const e=BM(t,"subagent_id"),r=BM(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:[this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Ce.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return He(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=He(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 He(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return He(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=qe(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)Je(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):Ze(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,ki.o1)(t,r),[o,i,a]=await Promise.all([(0,ki.DN)(n),(0,ki.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ki.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:FM(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===Ce.stop||e===Ce.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 qe(n,u))Ze(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=Ue(`Hook execution failed: ${n}`),r=it(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return NM.warn((0,be.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;if(1===t.length)return t[0];const r=Ye.includes(e),n=e===Ce.sessionStart,o=e===Ce.workspaceOpen,s=Ke.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=tt(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?rt(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=tt(i[e],l)}var a,c;return i}(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=it(e,Ue(`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=it(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=it(e,Ue(`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=it(e,Ue(`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=at(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=at(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=ot({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+LM}),{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+LM}),{success:!1,source:s,index:i})}const y=Qe(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=ot({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,be.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 nt(e)?st(0,{permission:"allow"}):e===Ce.beforeSubmitPrompt||e===Ce.sessionStart?st(0,{continue:!0}):e===Ce.stop?st(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=it(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=it(e,Ue(`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=vt.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:jM}):t.command;let w;if(m)w=e?bt(g):g;else if("windows_temp_file"===f){d=await(0,ti.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,ti.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 | ${bt(t)} }`+yt(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+yt(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=BM(n,"conversation_id")??void 0,v=BM(n,"session_id")??void 0,b=BM(n,"transcript_path"),S=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),k=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:S?.at(-1)??y:v,_=this.buildHookEnvironment({transcriptPath:b,sessionId:k,conversationId:y,executionEnv:i}),C={};for(const[e,t]of Object.entries(_))void 0!==t&&(C[e]=t);void 0!==a&&(C.CURSOR_PLUGIN_ROOT=a,C.CLAUDE_PLUGIN_ROOT=a);const E=(0,be.q6)(),x=new Ic.StringDecoder("utf8"),P=new Ic.StringDecoder("utf8");let I,R="",T="",A=null,$=!1;for await(const e of this.shellExecutor.execute(E,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:C,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),$=!0);break;case"stdout":R+=x.write(e.data);break;case"stderr":T+=P.write(e.data);break;case"exit":A=e.code,I=e.aborted}if(R+=x.end(),T+=P.end(),m&&!$)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const M=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:R,stderr:T,exitCode:A,duration:M}}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,ti.rm)(d,{recursive:!0,force:!0})}catch{}}}}class HM{constructor(e){this.config=e,this.configuredSteps=xM.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var qM=r("node:perf_hooks");function zM(e,t){void 0!==e&&t.length>0&&e.push(...t)}class GM 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 VM=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function KM({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 GM({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new VM.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ke).map((e=>{if(!function(e){return e===Ce.sessionStart||e===Ce.beforeSubmitPrompt||e===Ce.preToolUse||e===Ce.postToolUse||e===Ce.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}]})));class JM extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZM extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XM="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QM(e,t){return We(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XM}`)}function YM(e){return function(e){return e instanceof JM}(e)||function(e){return e instanceof ZM}(e)}const eD=(0,x.h)("generic-hooks");function tD(e,t,r,n){try{return KM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof GM)return eD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rD=e=>Math.round(1e3*e)/1e3;function nD(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,Xs.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 vl(e.signal,(()=>t.executeHookForStep(Ce.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));zM(i,tD(e,r,Ce.postToolUseFailure,h?.additional_context))}catch(t){eD.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await vl(e.signal,(()=>t.executeHookForStep(Ce.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));zM(i,tD(e,r,Ce.postToolUse,u?.additional_context))}catch(t){eD.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 oD(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await vl(e.signal,(()=>r.executeHookForStep(Ce.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=We(r);try{zM(n.hookContextCollector,KM({hookEventName:Ce.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof GM))throw t;eD.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))),zM(n.hookContextCollector,KM({hookEventName:Ce.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Ce.preToolUse,s.toolName)??!1,c=n instanceof GM;if(a){const e=Ue(`${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}}eD.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(YM(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 sD(e){return e.toolCallId}function iD(e,t,r,n){return{async execute(o,s,i){const a=cD(o,t),{hookContext:c,helpers:l}=nD(o,s,a,r,n,i);let u;try{u=await oD(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=qM.performance.now();try{const t=await e.execute(o,s,i),r=rD(qM.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(YM(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eD.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=rD(qM.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aD(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cD(e,t){const r=Pt(e),n=e.get(Et);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===Ce.preToolUse||e===Ce.postToolUse||e===Ce.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 lD(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uD{async readFile(e){try{return await ti.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await ti.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,ti.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lD(e))return!0;throw e}return!1}(e,t)}}class dD{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 Lr.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 Lr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Lr._G({result:{case:"success",value:new Lr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function hD(e){return!!e&&e.type!==Hi.vc.INSECURE_NONE&&e.type!==Hi.vc.UNSPECIFIED}async function pD({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Ce.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QM("Command execution",i.user_message);throw new JM(e)}if("ask"===i?.permission)return a=i.user_message,new Ir.In({kind:Ir.b.FORCE_PROMPT,reason:a});var a}const fD={toolName:$M,getToolCallId:sD,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 xr.Lt({result:{case:"rejected",value:new Ir.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=hD(r.sandboxPolicy);It(t,Ce.beforeShellExecution)&&Wr(r,await pD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class mD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,fD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const gD={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new xr.nt({result:{case:"error",value:new xr.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 wD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,gD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const yD={toolName:"ComputerUse",getToolCallId:sD,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Mg.ks({result:{case:"error",value:new Mg.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 vD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,yD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const bD={toolName:RM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Pr.Pi({result:{case:"rejected",value:new Pr.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 SD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,bD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const kD={toolName:MM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new HI.Ek({result:{case:"rejected",value:new HI.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 _D{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,kD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const CD={toolName:"Fetch",getToolCallId:sD,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Uw.uN({result:{case:"error",value:new Uw.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 ED{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,CD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xD={toolName:AM,getToolCallId:sD,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 ay.Ud({result:{case:"error",value:new ay.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 PD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,xD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ID={toolName:TM,getToolCallId:sD,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 _I.fv({result:{case:"rejected",value:new _I.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 RD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,ID)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TD=(0,x.h)("hooks-exec:mcp");function AD(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(AD):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&AD(e))))}function $D(e,t,r,n){try{return KM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof GM)return TD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class MD{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(Ce.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Ce.beforeMCPExecution)))return new rr.iz({result:{case:"error",value:new rr.Nh({error:`"${pr}" 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=cD(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,Xs.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(Ce.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{zM(i,KM({hookEventName:Ce.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof GM))throw t;TD.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 rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:QM("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(!AD(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ar.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){TD.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}zM(i,KM({hookEventName:Ce.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Ce.preToolUse,c)??!1,l=t instanceof GM;if(r){const r=Ue(`${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 rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:QM("MCP tool execution",r),isReadonly:!1})}})}TD.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=It(e,Ce.beforeMCPExecution)?await n.executeHookForStep(Ce.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QM("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new rr.iz({result:{case:"permissionDenied",value:new rr.HQ({error:t,isReadonly:!1})}})}const g=qM.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rD(qM.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){TD.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(Ce.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 rr._Z({content:{case:"text",value:new rr.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 rr._Z({content:{case:"text",value:new rr.zN({text:String(e.text)})}})):t.push(new rr._Z({content:{case:"text",value:new rr.zN({text:JSON.stringify(e)})}}))}else t.push(new rr._Z({content:{case:"text",value:new rr.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new rr.iz({result:{case:"success",value:new rr.QW({content:t,isError:r})}})}catch(t){return TD.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rD(qM.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(Ce.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return zM(c,$D(e,n,Ce.postToolUse,l?.additional_context)),l}catch(t){return void TD.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(Ce.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});zM(u,$D(e,n,Ce.postToolUseFailure,d?.additional_context))}catch(t){TD.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const DD={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new rr.kP({result:{case:"error",value:new rr.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 OD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,DD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FD={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 rr.ZD({result:{case:"error",value:new rr.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 ND{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,FD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jD={toolName:PM,getToolCallId:sD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new nr.sV({result:{case:"rejected",value:new nr.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?.(Ce.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${XM}`}(t,e instanceof Error?e.message:String(e));throw new ZM(r,e)}}((()=>o.executeHookForStep(Ce.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QM("File read",a.user_message);throw new JM(e)}}};class LD{constructor(e,t,r){this.wrappedExecutor=new ur(iD(e,t,r,jD))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UD={toolName:"RecordScreen",getToolCallId:sD,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new FR.Tj({result:{case:"failure",value:new FR.yH({error:t})}}),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 BD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,UD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function WD(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const HD={toolName:$M,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 Ir.W4({result:{case:"rejected",value:new Ir.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:WD(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||"";It(t,Ce.beforeShellExecution)&&Wr(r,await pD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:hD(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=WD(r);await o.executeHookForStep(Ce.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:hD(t.requestedSandboxPolicy),tool_use_id:i})}};class qD{constructor(e,t,r){this.wrappedExecutor=iD(e,t,r,HD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class zD{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 GD={toolName:$M,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 Ir.FI({event:{case:"rejected",value:new Ir.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Ir.FI({event:{case:"hookContext",value:new Ir.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new zD,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=hD(r.requestedSandboxPolicy);It(t,Ce.beforeShellExecution)&&Wr(r,await pD({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=hD(t.requestedSandboxPolicy);await n.executeHookForStep(Ce.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class VD{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cD(o,t),{hookContext:c,helpers:l}=nD(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oD(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aD(n,c))yield e;return}const h=qM.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=rD(qM.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aD(n,c))yield e;throw e}const f=rD(qM.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){eD.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 aD(n,c))yield e}}}(e,t,r,GD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class KD{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iD(e,t,r,function(e){return{toolName:IM,getToolCallId:sD,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 Rr.v3({result:{case:"error",value:new Rr.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?.(Ce.afterFileEdit))return;let s,i=!1;try{(await(0,ti.stat)(r.path)).size>262144?i=!0:s=await ac(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?.(Ce.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,ux.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(Ce.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ac(e),r=wa(t),o=Buffer.byteLength(t,"utf8");return new Rr.v3({result:{case:"success",value:new Rr.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 JD(e,t,r){return t===e.symbol}function ZD(e,t,r){return JD(Tr,e)?new qD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Ar,e)?new VD(t,r.hookExecutor,r.baseHookRequestExtractor):JD($r,e)?new KD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Kt,e)?new MD(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):JD(dr,e)||JD(hr,e)?new LD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Ft,e)?new RD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(_e,e)?new PD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Se,e)?new ED(t,r.hookExecutor,r.baseHookRequestExtractor):JD(ye,e)?new SD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(ve,e)?new _D(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Jt,e)?new OD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Zt,e)?new ND(t,r.hookExecutor,r.baseHookRequestExtractor):JD(de,e)?new mD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(he,e)?new wD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(we,e)?new vD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(Nr,e)?new BD(t,r.hookExecutor,r.baseHookRequestExtractor):JD(jr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new dD(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class XD{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===Rt.symbol)return new Dt(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ZD(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=ZD(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=Rt;yield[e,new Dt(this.hookExecutor)]}}const QD={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function YD(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>YD(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,oi.oG)(),args:[...pt,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,kl.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}}}function eO(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function tO(e){return"string"==typeof e&&e.length>0?e:void 0}function rO(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function nO(e){if(Array.isArray(e)&&e.every(rO))return e.map((e=>({id:e.id,value:e.value})))}class oO{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 sO(e,t={}){const r=await new xM(new uD,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?_M():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 HM(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...QD,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new WM(r,i,a,(t.createTerminalExecutor??YD)(),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 iO(e={}){return{createHooksRuntime:t=>sO(t.workspaceState,e)}}var aO=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function cO(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function lO(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 sy,l=(0,o.homedir)(),u=km(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,Fn.createClient)(aO.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await GA(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return KA.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,be.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new e$.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:gO(),getAgentSkills:async e=>[]};const p=(0,be.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new yg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=uO(t);return{getAllCursorRules:async t=>dO(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?gO():1===m.length?m[0]:new wg(m,(()=>Um)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=uO(t);return{getAllCursorRules:async t=>dO(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>dO(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new vg(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 Rg(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),b=R$(o.services.pluginBootstrapOutputs),S=b&&a?new Sg(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new $g((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,_=new wg([g,w,...S?[S]:[]],(()=>Um)),C=new AA([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),E=new Ag([v,...k?[k]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:S,pluginSubagentsService:k,mergedCursorRulesService:_,mergedAgentSkillsService:C,mergedSubagentsService:E};const x={cursorRulesService:_,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:E};return x},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 cO(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function uO(e){const t=Promise.all(e.allowedRoots.map(fO)),r=Promise.all(e.excludedRoots.map(fO));return async e=>{const[n,o,s]=await Promise.all([mO(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>hO(n,e)))&&o.some((e=>hO(n,e)))}}async function dO(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function hO(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function pO(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function fO(e){try{return pO(await(0,ti.realpath)(e))}catch{return pO(e)}}async function mO(e){try{return pO(await(0,ti.realpath)(e))}catch{return}}function gO(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function wO(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":d$.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":d$.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){d$.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=yO(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 lm(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,Fn.createClient)(aO.I,e.dashboardTransport),n=Wp((async()=>{try{return await r.getEffectiveUserPlugins(new e$.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Wp((async()=>{if(void 0===o)return{plugins:[]};try{const e=await lm(o);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||om(t)})).map((({key:e,entry:t})=>{const r=um(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 i=[];if(n.length>0)try{const e=n.map((e=>{const t=um(e.key);return new e$.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new e$.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new ph(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new ph(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=yO(d),p=new YA(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:I$,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)d$.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)d$.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 yO(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class vO{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const bO=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function SO(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 kO(e){const t=SO(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function _O(e){const t=SO(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 CO(e){const t=kO(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>kO(t.host).length-kO(e.host).length));for(const e of r){const r=kO(e.host);if(t===r)return _O({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return _O({reportedWorkspacePath:e.reported,suffix:n})}}}const EO={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class xO extends _A{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await cO(this.sessionMcpLease)}}}function PO(e){const t=new sy;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 vO,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new h_,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 h_:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Lw(u,d):new jw(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 EO;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return EO}}(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),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 _A(u):new xO(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(jr);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(jr,{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=>CO({value:e,roots:o})??e));for(const e of bO){const t=n[e];if(void 0===t||""===t)continue;const r=CO({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??SO(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 cO(c),e}}}}const IO=["cursorRulesService","getAgentSkills","subagentsService"],RO=new WeakSet;function TO(e){("object"==typeof e&&null!==e||"function"==typeof e)&&RO.add(e)}function AO(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&RO.has(e)}function $O(e,t){const r=Object.keys(t).filter((e=>!IO.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${IO.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of IO)Object.hasOwn(t,r)&&(e[r]=t[r])}async function MO(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&&(TO(s.cursorRulesService),TO(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&$O(n,e)}return n}catch(t){try{await DO(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 DO(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await cO(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||AO(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||AO(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 cO(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 OO=["project","user","team","mdm","plugins"],FO=new Set([...OO,"all"]);function NO(e){if(void 0===e||0===e.length)return LO([]);for(const t of e)if(!FO.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{...LO(OO),all:!0}}return LO(e.filter((e=>"all"!==e)))}function jO(e,t){return e[t]}function LO(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 UO=Object.freeze({}),BO=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:UO});async function WO(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 cO(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function HO(e={}){const t=function(e={}){return{workspace:e.workspace??c$,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({...BO.metadata,...e.metadata}),r={...BO,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await MO(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,On.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 WO(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 WO(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 MO(t,r,n);s?await DO(i,{disposeLocalExtensibility:l}):(o=i,await DO(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await DO(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class qO{async requestApproval(e){return{approved:!0}}}class zO{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 GO{async open(e,t){}async getDiagnostics(e,t){return[]}}class VO{async getCodebaseReference(e,t){}}class KO{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class JO{constructor(e){this.subagents=e.map((e=>new yn.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:yn.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}let ZO;function XO(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return ei(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,Qs.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,ni.statSync)(e).isDirectory()&&((0,ni.accessSync)(e,ni.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,Qs.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,Qs.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===ZO&&(ZO=function(e){return(0,ni.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),ZO)})}async function QO(e,t){const r=(0,s.dirname)(e);await(0,ti.mkdir)(r,{recursive:!0}),await(0,ti.writeFile)(e,t,"utf-8")}class YO{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=XO(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=z$({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new SM(this.projectDir,e.blobStore,QO,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new SM(this.projectDir,e.blobStore,QO,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=z$({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){d$.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,$n.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=z$({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=z$({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(XO(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const eF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,tF="User aborted/interrupted manually.";class rF{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.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,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 _n}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(!eF.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&Cn(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,On.C)(),o=function(e){const t=new $n.We,r=(0,$n.sh)(e),n=new $n.pH(new $n.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 YO({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:yn.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:yn.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 wn.a3({status:wn.jh.ACCEPTED}):new wn.a3({status:wn.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){d$.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 wn.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,On.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}async executeSubagentOnce(e,t,r,n){let o,s=0;const i=new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:r.prompt})})}}),a=new Gr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new u$,l={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&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return rn(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return on(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return cn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Do.tz({result:{case:"rejected",value:new Do.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return sn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},u={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const d=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==d&&""!==d?d:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new oe(f,function(e){const t=[te($r,Dr(e.errorMessage)),te(ye,Or(e.errorMessage)),te(Kt,Fr(e.errorMessage))];return e.wrapShell&&t.push(te(Tr,function(e){return{execute:async(t,r)=>new Ir.W4({result:{case:"permissionDenied",value:Mr(e,r)}})}}(e.errorMessage)),te(Ar,function(e){return{async*execute(t,r){yield new Ir.FI({event:{case:"permissionDenied",value:Mr(e,r)}})}}}(e.errorMessage)),te(de,function(e){return{execute:async(t,r)=>new xr.Lt({result:{case:"permissionDenied",value:Mr(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(te(he,function(e){return{execute:async(t,r)=>new xr.nt({result:{case:"error",value:new xr.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})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),i,a,l,m,n.agentStore.getBlobStore(),c,u,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:p$(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:tF}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return d$.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:tF}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:tF}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!Cn(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 wn.zJ({result:{case:"stillRunning",value:new wn.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 wn.zJ({result:{case:"complete",value:new wn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new wn.zJ({result:{case:"error",value:new wn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new wn.zJ({result:{case:"stillRunning",value:new wn.L5({agentId:r})}}):new wn.zJ({result:{case:"notFound",value:new wn.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 wn.zJ({result:{case:"stillRunning",value:new wn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new wn.zJ({result:{case:"complete",value:new wn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new wn.zJ({result:{case:"error",value:new wn.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 nF=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),oF=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),sF=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),iF=r("./src/agent/analytics.ts"),aF=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const cF={[Mg.w3.UNSPECIFIED]:"unspecified",[Mg.w3.LEFT]:"left",[Mg.w3.RIGHT]:"right",[Mg.w3.MIDDLE]:"middle",[Mg.w3.BACK]:"back",[Mg.w3.FORWARD]:"forward"},lF={[Mg.Dh.UNSPECIFIED]:"unspecified",[Mg.Dh.UP]:"up",[Mg.Dh.DOWN]:"down",[Mg.Dh.LEFT]:"left",[Mg.Dh.RIGHT]:"right"},uF={[Mg.EB.UNSPECIFIED]:"unspecified",[Mg.EB.TAP]:"tap",[Mg.EB.DOWN]:"down",[Mg.EB.UP]:"up"};function dF(e){return cF[e]??"unspecified"}function hF(e){return void 0===e?void 0:{x:e.x,y:e.y}}function pF({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:hF(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 fF(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 mF("tool-call-started",e.message.value);case"partialToolCall":return mF("partial-tool-call",e.message.value);case"toolCallCompleted":return mF("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"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=fF(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"modelCallCompleted":case void 0:return null;default:return e.message,null}}function mF(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:SF(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:kF(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:_F(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:CF(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:xF(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:PF(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:IF(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:TF(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:AF(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:MF(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:DF(t.mode)},...r?{result:OF(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:$F(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:FF(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:jF(e.status)})))},...r?{result:NF(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:hF(e.value.coordinate)};case"click":return{type:"click",coordinate:hF(e.value.coordinate),button:dF(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:dF(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:dF(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:hF(e.value.coordinate),direction:lF[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:uF[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?pF(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:gF(t),...r?{result:vF(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"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":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 gF(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:wF(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:yF(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function wF(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function yF(e){switch(e){case yn.FL.AGENT:return"agent";case yn.FL.PLAN:return"plan";default:return"unspecified"}}function vF(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:bF(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function bF(e){switch(e){case yn.qL.AGENT_REQUEST:return"agentRequest";case yn.qL.USER_REQUEST:return"userRequest";case yn.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function SF(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 kF(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 _F(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 CF(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]=EF(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:EF(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function EF(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 xF(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 PF(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 IF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:RF(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RF(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(RF)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function TF(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:LF(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 AF(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 $F(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 MF(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 DF(e){switch(e){case FR.$u.START_RECORDING:return"START_RECORDING";case FR.$u.SAVE_RECORDING:return"SAVE_RECORDING";case FR.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function OF(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 FF(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 NF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:jF(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function jF(e){switch(e){case aF.Vj.UNSPECIFIED:case aF.Vj.PENDING:return"pending";case aF.Vj.IN_PROGRESS:return"inProgress";case aF.Vj.COMPLETED:return"completed";case aF.Vj.CANCELLED:return"cancelled";default:return"pending"}}function LF(e){switch(e){case HI.h_.UNSPECIFIED:case HI.h_.ERROR:return"error";case HI.h_.WARNING:return"warning";case HI.h_.INFORMATION:return"information";case HI.h_.HINT:return"hint";default:return"error"}}const UF={type:"object",properties:{},additionalProperties:!0};function BF(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function WF(e){return"text"===e.type?new rr._Z({content:{case:"text",value:new rr.zN({text:e.text})}}):new rr._Z({content:{case:"image",value:new rr.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function HF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var qF=r("./src/agent/errors.ts");const zF="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 GF(e){return{async execute(){throw new Error(e)}}}function VF(e){var t;e.register(Tr,GF(zF)),e.register(Ar,(t=zF,{async*execute(){throw new Error(t)}})),e.register(de,GF(zF)),e.register(Br,GF(zF)),e.register(he,GF(zF)),e.register(Er,GF(zF)),e.register(ve,GF("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(ke,GF("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var KF=r("./src/agent/filesystem/executors.ts"),JF=r("./src/agent/filesystem/compose.ts"),ZF=r("./src/agent/filesystem/trees.ts"),XF=r("./src/agent/filesystem/walk.ts");const QF="/tmp",YF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function eN(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,XF.eI)(e.hostProjectDir),r=(0,XF.eI)(e.writePath);return"/"!==t&&(0,XF.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,XF.eI)(e.writePath):(0,XF.eI)(`${QF}/${r}`);if(!(0,XF.hJ)({path:n,prefix:QF}))return;const o=a().posix.basename(n),s=a().posix.join(QF,ml);return a().posix.dirname(n)===s&&YF.test(o)?a().posix.join(QF,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 tN{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,XF.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([rN(e,s.posix.join(t,".cursor/rules")),nN(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 rN(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,ir.PH)(r,(async t=>{const r=await oN(e,t),n=void 0===r?null:k(r);if(null!==n)return gg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function nN(e,t){const r=await oN(e,t);if(void 0!==r)return gg({path:t,body:b({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function oN(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const sN={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},iN={async exec(){throw new Error("git is not available in a FileSystem session")}},aN={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function cN(e){return{cursorRulesService:!0===e.includeProjectRules?new tN(e.fs,e.workspace):sN,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:iN,ignoreService:aN,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function lN(e,t){const r=t.workspace??"/",n=(0,KF.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:eN({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...cN({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:QF,excludeHooks:!0,excludeProjectMcp:!0}}var uN=r("./src/agent/executor-common.ts"),dN=r("./src/agent/native/vendored-tree-sitter.ts"),hN=r("./src/agent/platform-package-locator.ts"),pN=r("./src/agent/sdk-config.ts"),fN=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),mN=r("./src/agent/utils/logger.ts");const gN={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},wN=new Map;async function yN(e){try{const t=await async function(e){const t=await(0,uN.dC)(e,uN.EV);if(!t)return;const r=uN.EV.endsWith("/")?uN.EV.slice(0,-1):uN.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,uN.tF)(),"x-ghost-mode":(0,uN.U)(e)},body:JSON.stringify({})});if(!n.ok)return void mN.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return vN(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return gN;const r=new fN.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(vN(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,uN.tF)()}}}catch(e){mN.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,uN.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 mN.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),gN}}function vN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function bN(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var SN=r("./src/agent/tools-option.ts");class kN{async requestApproval(){return{approved:!0}}}function _N(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof _A))throw new qF.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Kt),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Lt}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new rr.iz({result:{case:"error",value:new rr.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:HF(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ar.Struct.fromJson(t.structuredContent):void 0;return new rr.iz({result:{case:"success",value:new rr.QW({content:t.content.map(WF),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 rr.iz({result:{case:"error",value:new rr.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new kN;e.resources.base.register(Kt,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Lt}(t)){const o=await hE(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 CN=new Set(["127.0.0.1","localhost","[::1]"]);function EN(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function xN(){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 PN={warn(){},error(){}},IN={log(){}};class RN{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${TN(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 TN(e){switch(e.type){case Ow.Shell:return"this shell command";case Ow.Mcp:return"this MCP tool call";case Ow.Write:return"this file edit";case Ow.Delete:return"this file deletion";default:return"this operation"}}function AN(e){return void 0!==e&&"insecure_none"!==e.type}async function $N(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,be.q6)().with(x._O,IN),a=NO(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&&CN.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}`);Uc=e}((0,pN.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(uN.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let d=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,uN.ly)(r.apiKey),(0,uN.mU)(r.apiKey)]),d=performance.now()-e}const h=r.workingDirectory||process.cwd();(0,dN.configureVendoredTreeSitterWorkspaceDir)(h);for(const e of r.dirs??[])(0,dN.configureVendoredTreeSitterWorkspaceDir)(e);const p=(0,Qs.Rv)((0,o.homedir)(),h),f={hostProjectDir:p,settings:{includeProjectRules:jO(a,"project"),subagentsService:new JO(r.customSubagents??[])}};let m;const g="win32"===process.platform?"rg.exe":"rg",w=process.env.CURSOR_RIPGREP_PATH;m=w&&(0,s.isAbsolute)(w)?w:(0,hN.hQ)({binaryName:g,excludedWorkspaceDir:h}),m||(m=(0,oi.xS)()),m&&(0,oi.J)(m);let y,v,b={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{y=(0,uN.KU)(r.apiKey,r.teamId);const e=(0,Fn.createClient)(aO.I,y),t=function(e){let t=wN.get(e);return t||(t=yN(e),wN.set(e,t),t.then((r=>{r===gN&&wN.get(e)===t&&wN.delete(e)}),(()=>{wN.get(e)===t&&wN.delete(e)}))),t}(r.apiKey);v=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};b=new i$(new n$(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===l?{}:{hostMcpBridgeUrls:l},isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){mN.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const S=performance.now(),k=r.apiKey?await(0,oi.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,_=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=AN(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,oi.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,hN.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,oi.St)({sandboxBinaryPath:r})}(t),!(0,oi.K3)(void 0,{ctx:e.initializationCtx}))throw new qF.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,oi.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:h,perUserSandboxPolicy:k,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,C=performance.now()-S,E=_?.defaultSandboxPolicy,P=_?.defaultSandboxPolicySources,I=AN(E),R=performance.now(),T=(()=>{const e=[],t=new Set;for(const n of[h,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),A={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},$=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=NO(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,oi.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new sy,h=new dl(d,a,n),p=new GO,f=new VO,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new zO(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=jO(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=_||jO(i,"project")||jO(i,"user")||b,x=jO(i,"project")||jO(i,"user")||jO(i,"mdm"),P=jO(i,"team"),I=P&&void 0!==e.dashboardTransport,R=jO(i,"project")||jO(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:jO(i,"project"),includeUserMcp:jO(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>HO({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:D$({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:wO({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:iO({includeProjectHooks:jO(i,"project"),includeUserHooks:jO(i,"user"),includeEnterpriseHooks:jO(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:lO({includeProjectExtensibility:jO(i,"project"),includeUserExtensibility:jO(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:PO({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=>new KO(new aT(e)),createSessionMcpLease:(t,r)=>D$({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{const r=w??new qO;return{pendingDecisionStore:r,fileChangeTracker:new Hw(t),permissionsService:new fP(h,r,g,a,t,e.respectAdminControls??!1)}}}),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 oO(new XD(e.resources,n.hookExecutor,(()=>function(e,t){const r=eO(t,tO,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:eO(t,tO,"generationId","generation_id")??r,model:eO(t,tO,"model")??"unknown",...Ve({modelId:eO(t,tO,"modelId","model_id"),modelParams:eO(t,nO,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new JO(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 d$.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:h,...void 0!==T?{dirs:T}:{},projectDir:p,teamSettingsService:b,initializationCtx:i,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:E,defaultSandboxPolicySources:P,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new RN:void 0,getNetworkAllowlistInfo:I?()=>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,oi.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,oi.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(b,(0,o.homedir)(),h):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:xN,getPowershellUtf8Options:async()=>{if(void 0===v)return A;try{const e=await v;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return A}},isLinkSharedPaymentTokenLogRedactionEnabled:bN(v),respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),M=performance.now()-R;let D,O;return(0,iF.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(d),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(M),load_sandbox_policy_ms:Math.round(C),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,d$.ni)(PN,(async()=>{const s=(0,c.VI)((0,be.q6)().withName("sdk.run").with(x._O,IN)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,On.C)(),u=t.mcpServersOverride,d=void 0===(p=t.customTools)?[]:Object.entries(p).map((([e,t])=>({clientKey:Lt,providerIdentifier:Lt,toolName:e,name:`${Lt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??UF,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:BF(t.annotations)},source:"internal"})));var p;let m;const g={...f,workspace:t.fileSystemWorkspace},w=void 0===t.fileSystem?void 0:(y=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),v=y,(0,JF.VL)({"/":v,[QF]:(0,ZF.Om)()}));var y,v;m=await $.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:d,...void 0===w?EN(t.sessionResources):lN(w,g)});const b=new Map;try{const s=m.resources.wrapped;_N(m,t.customTools),void 0!==w&&VF(m.resources.base);const c=t.blobStore??new $n.ve;let p=t.initialState??new Gr.Y9z({});const f=void 0!==t.model?new oF.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new oF.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,v=Array.isArray(y)?y.map((e=>{const t=(0,On.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,uN.v8)(r);return new sF.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=v.length>0?new sF.xv({selectedImages:v}):void 0,C=function(e){switch(e){case"agent":return Gr.xyI.AGENT;case"plan":return Gr.xyI.PLAN;default:return}}(t.mode),E=!0===e.summarize?new Gr.QFf({action:{case:"summarizeAction",value:new Gr.Scs}}):new Gr.QFf({action:{case:"userMessageAction",value:new Gr.Vtf({userMessage:new Gr.RGk({text:e.text,selectedContext:_,...void 0!==C?{mode:C}:{}})})}}),x={sendUpdate:async(e,t)=>{const r=fF(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return tn(e.id);case"webFetchRequestQuery":return nn(e.id);case"switchModeRequestQuery":return an(e.id);case"askQuestionInteractionQuery":return sn(e.id,new Do.tz({result:{case:"rejected",value:new Do.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return ln(e.id,new Kr.bK({result:{case:"success",value:new Kr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return un(e.id,new No.r$({result:{case:"success",value:new No.JH}}));case"replaceEnvArgs":return dn(e.id,new Fo.dV({result:{case:"failure",value:new Fo.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return hn(e.id,new Oo.HL({result:{case:"error",value:new Oo.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return pn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return fn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return mn(e.id,e.query.value.args?.description);case void 0:throw new qF.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new qF.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(D!==t.apiKey||!O){await Promise.all([(0,uN.ly)(t.apiKey),(0,uN.mU)(t.apiKey)]);const e=(0,uN.KU)(t.apiKey,r.teamId),n=Zs((0,Fn.createClient)(nF.N,e),{injectTraceHeaders:!0});O=new Ws(n),D=t.apiKey}const P=(0,uN.Vh)(O,(()=>{const e=(0,uN.KU)(t.apiKey,r.teamId),n=Zs((0,Fn.createClient)(nF.N,e),{injectTraceHeaders:!0}),o=new Ws(n);return O=o,D=t.apiKey,o})),I=function(e){return{...void 0!==e.allowedTools?{[SN.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[SN.VJ]:e.disallowedTools.join(",")}:{}}}(t),R=new rF({agentClient:P,getResources:async({agentId:e})=>{let r=b.get(e);return r||(r=await $.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:d,...void 0===w?EN(t.subagentInherit):lN(w,g)}),_N(r,t.customTools),void 0!==w&&VF(r.resources.base),r.resources.base.register(bn,T),r.resources.base.register(Sn,A),r.resources.base.register(kn,M),b.set(e,r)),r.resources.wrapped},mcpTools:d,workspacePath:h,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==w)&&Object.keys(I).length>0?{headers:I}:{},onSessionReleased:e=>{const t=b.get(e);t&&(t.dispose(),b.delete(e))}}),T=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 wn.vS({result:{case:"error",value:new wn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new wn.vS({result:{case:"error",value:new wn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new wn.vS({result:{case:"success",value:new wn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new wn.vS({result:{case:"success",value:new wn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof en)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof vn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new wn.vS({result:{case:"error",value:new wn.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}}}(R),A=(k=R,{execute:(e,t)=>k.awaitBackgroundRunBounded(e,t)}),M=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(R);m.resources.base.register(bn,T),m.resources.base.register(Sn,A),m.resources.base.register(kn,M);const F=$.services.hooksRuntime,N="object"==typeof(S=F)&&null!==S&&"workspacePath"in S&&"string"==typeof S.workspacePath&&"createSessionRuntime"in S&&"function"==typeof S.createSessionRuntime?F:void 0,j=void 0!==N&&void 0===w&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Ce.sessionStart)||t.hooksConfigLease.hasHookForStep(Ce.sessionEnd)||t.hooksConfigLease.hasHookForStep(Ce.stop)||t.hooksConfigLease.hasHookForStep(Ce.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(Ce.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),is_background_agent:!1},r=await n.executeHookForStep(Ce.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){d$.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Ce.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?Ve(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Ce.sessionEnd,r)}catch(e){d$.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Ce.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Ce.beforeSubmitPrompt,t)}catch(e){d$.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Ce.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Ce.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(Ce.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Ce.stop,t)}catch(e){d$.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Ce.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Ve(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Ce.stop,t)}catch(e){d$.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:N,sessionState:m.state,metadata:m.metadata}):void 0,L=new YO({workspacePath:h,conversationId:l,blobStore:c}),U=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new u$;let a;const c=new Map,l=(e,t)=>{const r=c.get(e);void 0!==r&&(c.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let u;const d=[],h=e=>{for(const t of d.splice(0))t.resolve(e)},p=()=>{if(0===d.length)return;const e=d.map((e=>e.text)).join("\n\n");return h("complete_delivered"),w$(e)},f=r.interactionListener,m={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:c.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):(c.delete(t),s.resolve(e))}}await f.sendUpdate(e,t)},query:(e,t)=>f.query(e,t),...void 0!==f.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>f.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==f.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>f.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let g=r.initialState;const w={async handleCheckpoint(e,t){g=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>g};let y="completed";const v=Date.now(),b=p$(function(e,t){if((0,$n.TU)(t))return t;const r=f$.get(e);if(void 0!==r)return r;const n=(0,$n.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return f$.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=g$(r,0,m$(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw y="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==y)throw e;d$.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,d=0;for(;s;){const e=g$(r,d,m$(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){d$.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,On.C)();try{await r.agentClient.run(o,g,s,void 0,m,r.resources,r.blobStore,i,w,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:b,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw y=y$(t)?"aborted":"error",v$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...c.keys()])l(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw y="error",e}const f="string"==typeof t?t.trim():"";let v;if(f.length>0)v=w$(f);else{const t=new AbortController;u=t;try{v=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw y=o.signal.aborted||y$(r)?"aborted":"error",v$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{u=void 0}void 0===v?v=p():h("revert_to_followup")}void 0!==v?(d+=1,i.resetStream(),s=v):s=void 0}})().finally((async()=>{h("revert_to_followup");const e=Date.now()-v;try{await(n?.onSessionEnd?.(y,e))}catch(e){d$.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){d$.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=u;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{d.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,On.C)(),n=new Promise((e=>{const t=setTimeout((()=>{l(r,"revert_to_followup")}),15e3);t.unref?.(),c.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new Gr.QFf({action:{case:"injectContextAction",value:new Gr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new Gr.oW$({userMessage:new Gr.RGk({messageId:(0,On.C)(),text:e})})}})}})),await n}catch(e){return l(r,"revert_to_followup"),d$.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,E,{agentClient:P,interactionListener:x,resources:s,blobStore:c,initialState:p,conversationId:l,mcpTools:d,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:f,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(I).length>0?{headers:I}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:j,async nextAction(e,t){const r=await R.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new Gr.QFf({action:{case:"backgroundTaskCompletionAction",value:new Gr.Kwc({completions:e.map((e=>new Gr.KFq({taskId:e.agentId,kind:Gr.aZc.SUBAGENT,status:"success"===e.status?Gr.uHL.SUCCESS:"aborted"===e.status?Gr.uHL.ABORTED:Gr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){p=e,L.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),B=U.done.finally((async()=>{try{await R.awaitBackgroundWorkers()}finally{await L.waitForPendingWrites().catch((()=>{}));for(const e of b.values())try{await e.dispose()}catch(e){mN.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}b.clear(),await m.dispose()}})).catch((e=>{throw e}));return{abort(){U.abort(),a()},done:B,steer:e=>U.steer(e)}}catch(e){for(const e of b.values())try{await e.dispose()}catch{}throw b.clear(),await m.dispose(),e}var S,k})),async reload(){await $.reload()},async dispose(){await $.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)},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>q,ME:()=>L,_N:()=>H,b6:()=>j,bi:()=>P,mD:()=>A,vc:()=>O});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=F(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<=I&&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}}(F(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=F(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=F(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=F(e);return v.test(t)||function(e){const t=F(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=F(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=F(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(R.has(e))return R.get(e);R.size>=I&&R.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=`${F(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 R.set(e,t),t}const I=2048,R=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("*")&&F(s)===F(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=N(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!F(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(F(r.hostname)!==F(o))return}return r}}function O(e,t){if(A(e,t))return!0;let r;return T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=N(t),T.set(t,r)),!!r&&h(r.hostname,e)}function F(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function N(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 j(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function L(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=j(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(F(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 U(e){const t=e?.trim();return t&&t.length>0?t:void 0}function B(e){return U(e)?.toLowerCase()}function W(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function H({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=U(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=>function(e,t){const r=B(e.builtinServer),n=B(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=U(e.command),s=U(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&&O(s,t.url);return i&&a}(e,t)))}(c,t),d=W(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||W(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!==U(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!==U(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:()=>Yr,Ls:()=>d,SandboxUnsupportedError:()=>Ft,J:()=>_,St:()=>jt,Fn:()=>Qr,ue:()=>o,r5:()=>he,oG:()=>Rr,Ko:()=>P,CG:()=>je,W1:()=>V,G6:()=>Xr,_B:()=>Ie,OK:()=>xe,$b:()=>Pe,K3:()=>Bt,tv:()=>Oe,wG:()=>qe,fZ:()=>Ge,s9:()=>Ue,XX:()=>He,T6:()=>Te,Po:()=>Re,$6:()=>Me,l7:()=>Fe,xS:()=>k,resolveSandboxPolicyForWorkspace:()=>Je,spawnInSandbox:()=>Lt,Xw:()=>x});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function i(e){const t={...e};for(const e of s)delete t[e];return t}const a=[["core.quotePath","false"]];function c(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=y(e,r);if(p.existsSync(n))return v(n,t,r)}for(const o of n){const n=y(`${e}${o}`,r);if(p.existsSync(n))return v(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:h.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:h.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 b;const S=["/usr/local/bin","/usr/bin","/bin"];function k(){const e=v("rg",[]).cmd;return"rg"!==e?e:void 0}function _(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");b=e}function C(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 E(e,t){const r=(0,h.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=C(e);return void 0!==t?e[t]??"":""}(e).split(h.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=S),function(e,t){const r=C(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(h.delimiter))}function x(e){return b&&(0,h.isAbsolute)(b)?{...E(e,b),CURSOR_RIPGREP_PATH:b}:e}function P(){if(!b)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return b}const I="win32"===process.platform;function R(e){return!I&&!!e?.SUDO_ASKPASS}function T(e){return R(e)?"alias sudo='sudo -A'; ":""}function A(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 M=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function D(e){M.some((t=>$(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function O(e){$(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const F="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",N=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],j=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${N.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${F}";; esac; `,L=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${N.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${F}" } else { $env:MAVEN_OPTS = '${F}' }\n}`;var U=r("node:crypto"),B=r("node:os"),W=r("../utils/dist/workspace-paths.js"),H=r("../utils/dist/test-resets.js");let q;function z(e,t){const r=(0,p.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function G(e){try{(0,p.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function V(e){return K(e,{create:!1})}function K(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,h.join)((0,B.tmpdir)(),`cursor-sandbox-${(0,W.r_)((0,h.resolve)(e))}`);try{for(const e of[n,(0,h.join)(n,"tmp")])if(t&&G(e),!z(e,r))return;return n}catch{return}}(0,H.J)((function(){q=void 0}));const J='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function Z(e=(0,h.join)((0,B.tmpdir)(),"cursor-sandbox-cache",function(){return q||(q=(0,U.randomBytes)(16).toString("hex")),q}())){return{NPM_CONFIG_CACHE:(0,h.join)(e,"npm"),PNPM_STORE_PATH:(0,h.join)(e,"pnpm-store"),GOCACHE:(0,h.join)(e,"go-build"),GOMODCACHE:(0,h.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,h.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,h.join)(e,"pip"),UV_CACHE_DIR:(0,h.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,h.join)(e,"bun"),YARN_CACHE_FOLDER:(0,h.join)(e,"yarn"),npm_config_devdir:(0,h.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,h.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,h.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,h.join)(e,"turbo"),GRADLE_USER_HOME:(0,h.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,h.join)(e,"conda"),POETRY_CACHE_DIR:(0,h.join)(e,"poetry"),GEM_SPEC_CACHE:(0,h.join)(e,"gem-specs"),BUNDLE_PATH:(0,h.join)(e,"bundle"),COMPOSER_HOME:(0,h.join)(e,"composer"),HOMEBREW_CACHE:(0,h.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,h.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,h.join)(e,"nx"),NUGET_PACKAGES:(0,h.join)(e,"nuget"),CCACHE_DIR:(0,h.join)(e,"ccache"),CP_HOME_DIR:(0,h.join)(e,"cocoapods")}}var X=r("node:fs/promises"),Q=r("node:child_process"),Y=r("node:string_decoder"),ee=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),te=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class re extends Error{constructor(e,t,r,n,o,s){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=s,this.command=r,this.args=n,"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,re)}}function ne(e,t,r){r=r??{};let n=new ee.Observable((n=>{const{encoding:o,timeout:s,...i}=r,{cmd:a,args:c}=v(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const u=(0,Q.spawn)(a,c,i);r.processInfo&&void 0!==u.pid&&(r.processInfo.pid=u.pid);let d=null;s&&s>0&&(d=setTimeout((()=>{u.killed||u.kill();const e=new re(`Process timed out after ${s}ms`,-1,a,c);n.error(e)}),s));const h={stdout:new Y.StringDecoder(o||"utf8"),stderr:new Y.StringDecoder(o||"utf8")},p=t=>o=>{if(o.length<1)return;let s;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);try{s="string"==typeof o?o:h[t].write(o)}catch{s=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}s.length>0&&n.next({source:t,text:s})},f=e=>{const t=h[e].end();t.length>0&&n.next({source:e,text:t})},m=new ee.Subscription;if(l)if(u.stdin){const e=u.stdin;m.add(l.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let g=null,w=null,y=!1;if(u.stdout){const e=new ee.AsyncSubject;w=e,u.stdout.on("data",p("stdout")),u.stdout.on("close",(()=>{f("stdout"),e.next(!0),e.complete()}))}else w=(0,ee.of)(!0);if(u.stderr){const e=new ee.AsyncSubject;g=e,u.stderr.on("data",p("stderr")),u.stderr.on("close",(()=>{f("stderr"),e.next(!0),e.complete()}))}else g=(0,ee.of)(!0);return u.on("error",(e=>{y=!0,d&&clearTimeout(d),n.error(e)})),u.on("close",(e=>{y=!0,d&&clearTimeout(d);const t=(0,ee.merge)(w,g).pipe((0,te.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new re(`Process failed with exit code: ${e}`,e,a,c);n.error(t)}))})),m.add(new ee.Subscription((()=>{y||(d&&clearTimeout(d),u.kill())}))),m}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;n=n.pipe((0,te.L5)({count:e,delay:(e,r)=>{if(e instanceof re&&0!==e.exitCode)return(0,ee.timer)(t);throw e}}))}return r.split?n:n.pipe((0,te.Tj)((e=>e?.text)))}function oe(e,t,r){return r?.split?(n=ne(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof re){const n=new re(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof re){const t=new re(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(ne(e,t,{...r??{},split:!1}));var n}var se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const ie=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ae=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],ce=(e,t)=>t.flatMap((t=>ae.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),le={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},ue=e=>[...ie,...le[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),de=[{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"},...ue("linux"),...ce("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"},...ue("darwin"),...ce("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 he(e=process.platform,t=B.homedir(),r={}){const n=[];for(const o of de){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,h.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,p.lstatSync)(s).isFile();break;case"home-dir":e=(0,p.lstatSync)(s).isDirectory();break;case"bundled":e=(0,p.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const pe=[{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:"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"}];function fe(e){const t=pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function me(e){const t=pe.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}pe.filter((e=>"git"===e.type)).map((e=>e.pattern)),pe.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const ge=[];let we=null,ye=null;let ve=null;const be=new Map;const Se="win32"===process.platform||"darwin"===process.platform;function ke(e){if(!e.endsWith(h.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function _e(e){return e.endsWith(h.sep)?e:e+h.sep}function Ce(e,t){const r=ke(t);if(Se){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(_e(n))}return e===r||e.startsWith(_e(r))}function Ee(e,t){const r=ke(e);return Se?(0,h.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,h.relative)(r,t).replace(/\\/g,"/")}async function xe(e,t){if(Ce(e,t)){const r=Ee(t,e);if((null===we&&(we=se({ignoreCase:!0}),we.add(pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),we).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=be.get(e);if(t)return t;const r=await(0,X.stat)((0,h.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return be.set(e,t),t}const n=await async function(e){try{const t=await oe("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,h.dirname)((0,h.resolve)(e,t.trim()))}catch{return null}}(e),o={isWorktree:!0,gitDirParent:n??e};return be.set(e,o),o}(t);if(Ce(e,n)){const t=Ee(n,e);if((null===ye&&(ye=se({ignoreCase:!0}),ye.add(pe.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ye).ignores(t))return!0}if(r&&Ce(e,t)&&".git"===Ee(t,e))return!0;for(const t of function(){if(null!==ve)return ve;const e=B.homedir(),t=[];for(const r of pe)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,h.join)(e,r.pattern))}return ve=t,t}())if(Ce(e,t))return!0;return!1}function Pe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ie(e){return void 0!==e&&"allow"===e.default}function Re(){return{version:1,default:"deny"}}function Te(){return{version:1,default:"allow"}}var Ae=r("../utils/dist/path-utils.js");function $e(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 Me(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:$e(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function De(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","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 Oe(e,t){const r=await async function(e,t){try{const r=await(0,X.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==De(n))return{success:!1,error:`Invalid sandbox policy: ${De(n)??""}`};let o=Me(n);return t&&(o=Fe(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 Fe(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ae.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ae.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ae.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var Ne=r("../utils/dist/safe-spawn-cwd.js");function je(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Le(...e){return e.some((e=>!0===e))}function Ue(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ze(e));return[...t]}const Be=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]function(...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=ze(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ze);let r=new Set(t[0].map(ze));for(let e=1;en.has(e))))}return[...r]}(...e);function He(...e){return Be.merge(...e)}function qe(...e){return We(...e)}function ze(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Ge(...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 Ve(...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)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function Ke(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Je(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,Ne.$f)(e))return Ze(t,{workspaceDir:e});const n=r.stat??X.stat,o=r.spawnPromise??oe,s=await n((0,h.join)(e,".git")).then((e=>e),(()=>null)),i=s?.isFile()??!1,a=null!==s;if("workspace_readwrite"===je(t)){let r=e;if(i){const n=await o("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,h.resolve)(e,t.trim())),(()=>null));if(n){r=(0,h.dirname)(n);const o=t.perRepo,s=o?.ignoreMapping;t={...t,perRepo:{...o,type:"workspace_readwrite",additionalReadwritePaths:[...o?.additionalReadwritePaths??[],n],ignoreMapping:s,writeProtectionMapping:Ve(o?.writeProtectionMapping,me(e))}}}}if(a)return Ze(t,{workspaceDir:e,gitDirParent:r})}return Ze(t,{workspaceDir:e})}function Ze(e,t){return function(e,t){const r=function(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}(e);if(void 0===r)return tt({},t);switch(r){case"workspace_readwrite":return tt(Qe(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ye(e,t),o={policy:et({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,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Qe(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:et({type:"insecure_none",allowlistEscalated:Le(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Ke(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Le(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Ke(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Qe(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Xe(e,t){return e?.type===t}function Qe(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Xe(r,t)?r:void 0,perRepo:Xe(n,t)?n:void 0,teamAdmin:Xe(o,t)?o:void 0}}function Ye(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!==ge.length)return{version:1,deny:[...ge]}}(),r=B.homedir(),n=[];for(const e of pe)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,h.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:fe(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")},p=Le(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 f=Le(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=Ke(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=Ke(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?Ue(s.additionalReadPaths):Ue(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=Ue(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=Ge(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=Ke(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=Le(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=Ke(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=Ve(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=function(e){const t=pe.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??i);return{disableTmpWrite:p||void 0,networkPolicyStrict:f,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:Ve(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function et(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 tt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ye(e,t),a=Ue(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:et({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,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var rt=r("../utils/dist/workload-spawn.js"),nt=r("../context/dist/logger.js"),ot=r("../context/dist/core.js");const st=Q.execFile,it=new WeakMap;function at(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}let ct=0;function lt(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?h.resolve(e):h.resolve(h.join(B.homedir(),".cursor","sandbox-policies"))}();p.mkdirSync(e,{recursive:!0,mode:448});try{p.chmodSync(e,448)}catch{}const t=Date.now();return t-ct>=9e5&&(ct=t,function(e){let t;try{t=p.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=h.join(e,n);try{const e=p.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&p.unlinkSync(t)}catch{}}}(e)),e}function ut(e){const t=lt(),r=U.randomBytes(8).toString("hex"),n=h.join(t,`sandbox-policy-${r}`);return p.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const dt="darwin"===process.platform,ht="linux"===process.platform,pt=(0,nt.h)("shell-exec:sandbox");function ft(e){const t=lt();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let mt,gt=!0,wt=!1;function yt(){return mt}function vt(e){"linux"===process.platform&&Object.assign(e,x(e))}let bt=null,St=null,kt=null,_t=null,Ct=!1,Et=null;function xt(e){return{...e,additionalReadonlyPaths:ft(e.additionalReadonlyPaths)}}function Pt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return Mt(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,p.existsSync)(r)&&(0,p.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=function(e,t=e=>p.existsSync(e)){if((0,Ne.$f)(e))return!0;let r=h.resolve(e);for(;;){try{if(t(h.join(r,".git")))return!0}catch{}const e=h.dirname(r);if(e===r)return!1;r=e}}(r),s=!ht||o?t??{}:{},i={...n};for(const[e,t]of Object.entries(s))i[e]?i[e]=[...i[e],...t]:i[e]=t;if(0!==Object.keys(i).length)return Mt(i)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=gt;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=P()}catch{}for(const o of he(e,B.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=B.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=h.join(B.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=h.basename(e);if((o.includes("*")||o.includes("?"))&&(e=h.dirname(e)),!e||"."===e)continue;const s=h.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Pe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function It(e){const t={sandbox:e};return ht&&function(){const e=wt;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Rt(e){if(null!==bt)return bt;try{const t=yt();return pt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(bt=p.existsSync(t),bt?pt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(bt)}`):(St=new Error(`Sandbox binary not found at ${t}`),pt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),bt):(St=new Error("Sandbox binary path was not configured"),bt=!1,pt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return St=t instanceof Error?t:new Error(String(t)),bt=!1,pt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Tt(e){if(null!==_t)return _t;const t=e??(0,ot.q6)();if(pt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Rt(t)){const e=St?.message||"Binary check failed";return kt=e,pt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),_t=!1,_t}if("win32"===process.platform)return kt="Windows sandbox helper only provides network proxy, not filesystem isolation",pt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),_t=!1,_t;if("darwin"===process.platform)return kt=null,pt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),_t=!0,_t;const{binaryPath:r,args:n,env:o}=function(e,t){const r=It(Pt(xt({type:"workspace_readwrite"}),t)),n=String(yt());pt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),pt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return vt(o),{binaryPath:n,args:["--policy",ut(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,rt.D9)(Q.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:At,env:o,shell:!1});const s=Date.now()-e;return kt=null,pt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),_t=!0,_t}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return pt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),pt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&pt.error(e,`[sandboxPreflight] Stderr: ${o}`),kt=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"}`,_t=!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,H.J)((function(){_t=null,Ct=!1,Et=null,kt=null,bt=null,St=null}));const At=15e3;function $t(e,t=[],r={},n){const s=(0,ot.q6)();if(r.env=o(r.env),!Rt(s))throw new Error(`Sandbox binary not available: ${St?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,rt.D9)(Q.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let c=e,l=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",l=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",l=["-c",`${e} ${t.join(" ")}`]));const u=Pt(xt(n),a),d=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return K(e.cwd,{create:!0})}(u);d&&(u.additionalReadwritePaths=[...u.additionalReadwritePaths??[],d]);const p=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Pe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),f=It(u);void 0!==p&&(f.networkPolicy=p),!1===n.networkPolicyStrict&&(f.networkPolicyStrict=!1);const m=["--policy",ut(JSON.stringify(f)),"--",c,...l],g=o(process.env),w={..."linux"===process.platform?i(g):g,..."linux"===process.platform&&r.env?i(r.env):r.env,CURSOR_SANDBOX:"native"};if(vt(w),d){const e=function(e,t,r){const n=function(e){const t=(0,h.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,h.join)(t,"sh-")}}(e);if(r){const r=Z();for(const[o,s]of Object.entries(Z(e)))t[o]===r[o]&&(n[o]=s)}return n}(d,w,n.enableSharedBuildCache);Object.assign(w,e),w.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),w.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const y={cwd:r.cwd||s,env:w,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,rt.D9)(Q.spawn,String(yt()),m,y);return dt&&t.pid&&function(e,t){it.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,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function Mt(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Dt(t):t;o[e]=r;const n=Ot(e);n!==e&&(o[n]=r)}return o}function Dt(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ot(e,t){if((0,Ne.$f)(e))return e;try{return(t??p.realpathSync)(e)}catch{return e}}class Ft extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Nt="darwin"===process.platform;function jt(e){!function(e){P();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;mt||(mt=t),void 0!==r&&(gt=r),void 0!==n&&(wt=n)}(e)}function Lt(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...Z(),...r.env}}),"insecure_none"!==n.type){if(Tt())return $t(e,t,r,n);const o=kt;throw new Ft(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Q.spawn,spawnWorkload:rt.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function Ut(e){return Nt?async function(e){const t=it.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,rt.D9)(st,"/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:at(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:at(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 Bt(e,t){if(Nt)try{(0,p.accessSync)("/usr/bin/sandbox-exec",p.constants.X_OK)}catch{return!1}return Tt(t?.ctx)}var Wt=r("node:stream"),Ht=r("../context/dist/otel.js"),qt=r("../utils/dist/writable-iterable.js");const zt="--",Gt='builtin eval "$1" 3<&- 4>&-',Vt=50,Kt=262144;class Jt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Vt,this.maxBufferedBytes=t?.maxBufferedBytes??Kt}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 Jt(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([Xt(e.stdout,r,t),Qt(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 Xt(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 Qt(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Yt;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Yt||(Yt={}));const er={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function tr(e,t,r,n={spawn:Q.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function rr(e,t=[],r={},n,o){const s=Lt(e,t,{...r,env:x(r.env??process.env)},n);if(o){const e=function(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}({platform:process.platform,detached:!0===r.detached}),t=()=>{if(!s.pid)return;tr(s,e,"SIGTERM");const t=setTimeout((()=>{!s.killed&&s.pid&&tr(s,e,"SIGKILL")}),1e3);"process_group"!==e&&s.once("exit",(()=>{clearTimeout(t)}))};o.aborted?t():(o.addEventListener("abort",t,{once:!0}),s.once("exit",(()=>{o.removeEventListener("abort",t)})))}return s}function nr(e){const t=[];return e?.on("data",(e=>{t.push(e)})),()=>Buffer.concat(t).toString("utf8")}function or(e){e?.on("error",(()=>{}))}const sr="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 ir(e,t){return 126===e&&""===t}function ar(){return"win32"!==process.platform}function cr(e,t){const r=e.stdio.at(5);r instanceof Wt.Writable&&(or(r),r.end(`${t}\0`))}function lr(e,t){e&&(or(e),e.write(t),e.end())}function ur(e,t){if(!e)return;or(e);const r=new Y.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 dr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function hr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function pr(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 fr="__CURSOR_BASH_STATE_START__",mr="__CURSOR_BASH_STATE_END__";var gr=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 wr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=v("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:v("bash",[]).cmd}function yr(e){if("win32"!==process.platform)return e;const t=h.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===h.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function vr(e){const t=e.pipeStdin?Gt:`${Gt} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?sr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+J+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class br{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new br(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;h.resolve(t)===h.resolve(this.cwd)&&(this.cwd=void 0===r||h.resolve(r)===h.resolve(t)||(0,Ne.A)(r)?(0,Ne.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{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}(n,(0,Ht.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,qt.Jt)(),a=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...er,...e?.env};return c(n),"win32"===t&&(D(n),O(n)),n}(r),u=T(l),d=this.useFileStateTransport,p=!d&&!this.commandPipeUnreadable;let f,m,g;if(d){f=await(0,X.mkdtemp)(h.join(B.tmpdir(),"cursor-bash-state-")),m=h.join(f,"state-in"),g=h.join(f,"state-out"),await(0,X.writeFile)(m,this.state,"utf8"),await(0,X.writeFile)(g,"","utf8").catch((()=>{}));const e=yr(m),t=yr(g);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const w=function(e){return["-O","extglob","-c",e.script,zt,...void 0===e.command?[]:[e.command]]}({script:vr({pipeCommand:p,useFileTransport:d,sudoAliasInjection:u,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?j:""}),command:p?void 0:t}),y=wr(this.userTerminalHint);if(!y)throw new Error("Can't find Bash");const v=r?.sandboxWorkspaceRoot??a,b=(await Je(v,r?.sandboxPolicy)).policy,S="insecure_none"!==b.type?{...b,sandboxWorkspaceRoot:v}:b;let k="";const _=async()=>{if(d){if(!g)return void(k=this.state);try{k=await(0,X.readFile)(g,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),k=this.state}}},C=async()=>{if(f)try{await(0,X.rm)(f,{recursive:!0,force:!0})}catch{}};let E;(0,Ne.$Y)(a)&&(0,Ht.HF)(o.ctx,Ne.yo);try{E=rr(y,w,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:a,detached:!0},S,r?.signal)}catch(e){throw await C(),e}E.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:E.stdin??void 0,pid:E.pid})}catch(e){}}));const x=Zt({stdout:E.stdout,stderr:E.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});E.on("error",(async e=>{if((0,Ne.fK)(e,a)){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await C(),i.throw(e)}));let P=null,I=null,R=null,A=!1;const $=async e=>{if(A)return;if(A=!0,R&&(clearTimeout(R),R=null),(0,Ht.HF)(o.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await C(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,Ne.wz)({exitCode:P,stdoutBytes:x.stdoutBytes,stdoutPrefix:x.stdoutPrefix,cwd:a})&&""===k;if(t&&x.dropHeldStdout(),await x.flush(),p&&ir(P,k)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await C(),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,Ne.Vn)(a))}if(!r?.signal?.aborted){await _();const e=`${fr}\n`,t=`${mr}\n`;if(k.startsWith(e)&&k.endsWith(t)){let t=k.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=dr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(S.captureDenies)try{const e=await Ut(E);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:P,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await C()};E.on("exit",((e,t)=>{P=e,I=t;const n=r?.closeTimeout??5e3;n>0&&(R=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),$(!1)}),n))})),E.on("close",(async()=>{await $(!0)}));const M=E.stdio[3],F=E.stdio[4],N=M instanceof Wt.Writable?M:null,L=F instanceof Wt.Readable?F:null;p&&cr(E,t),d||(lr(N,this.state),ur(L,(e=>{k+=e}))),yield*i}catch(e){n.error=e,n.hasError=!0}finally{gr(n)}}}async function Sr(e){const t={...process.env,...er,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=wr(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const s=rr(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal),i=nr(s.stdout);s.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=pr(hr(i(),r),fr,mr)??`${process.cwd()}\n`,{cwd:c,rest:l}=dr(a),u="win32"===process.platform,d="win32"===process.platform?process.cwd():c;return new br(d,l,e?.userTerminalHint,u)}var kr=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 _r{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new _r((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={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})}(n,(0,Ht.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{kr(n)}}}const Cr="\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",Er=e=>e.map((e=>`'${e}'`)).join(", "),xr=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $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 $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\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 if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.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; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\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 'either' }\n if ($__cursorFull) {\n # A full window 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 }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\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 # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\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 -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\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 # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\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}\n'@\n if (-not $__cursorHasEncodingDefault) {\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 Get-Content -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 $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\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:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # 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 @(${Er([".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 @(${Er([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${Er([".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 @(${Er([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${Er([".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 }\n }\n} catch { }\n`,Pr=String.raw` + try { + if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) { + function global:__cursorUtf8FromLatin1 { +diff --git a/dist/esm/305.js b/dist/esm/305.js +index b56f18ebc41b57f91b4dbf3df510288c056a05b8..c3966b9e0755f2716649eaf524cce5814ed7d036 100644 +--- a/dist/esm/305.js ++++ b/dist/esm/305.js +@@ -1,4 +1,5 @@ +-import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=305;export const __webpack_esm_ids__=[305];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>RN});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../context/dist/otel.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});class c{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,i.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{a(e)}}}function l(e){return e instanceof Error?e.message:String(e)}function u(e){return"Failed to read skill file: "+l(e)}function d(e){return"Invalid skill frontmatter: "+l(e)}function h(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const p=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function f(e){return e.toLocaleString("en-US")}var m=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const g=102400;function w(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function y({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>g?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=g;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 v(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function b(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$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(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=e.slice(r+1).trim(),c=v(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=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=v(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 S(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 k(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const _=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];var C=r("../context/dist/logger.js"),E=r("../metrics/dist/index.js"),x=r("../proto/dist/generated/agent/v1/exec_pb.js"),P=r("../utils/dist/writable-iterable.js");const I=/https?:\/\/\S+/gi,R=/[)"'<>,.;:\]}]$/;function T(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&R.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(I,T),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const M=(0,C.h)("SimpleControlledExecManager"),D=(0,E.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),O=(0,E.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),F=(0,E.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),N={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 j extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function L(e){return e instanceof j?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class U{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}),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 B{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 x.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class W{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t}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,P.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new x.$Y({message:{case:"heartbeat",value:new x.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new x.$Y({message:{case:"streamClose",value:new x.D9({id:t.id})}})),O.increment(r,1,{exec_case:o})}catch(e){if(e instanceof P.W2)return;F.increment(r,1,{exec_case:o}),await a.write(new x.$Y({message:{case:"throw",value:new x.Fu({id:t.id,error:e instanceof Error?$(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:L(e)})}}))}finally{const e=performance.now()-u;D.histogram(r,e,{exec_case:o}),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:N[s])??`No handler found for server message of type ${s}`;return M.error(e,i,{messageCase:s}),F.increment(e,1,{exec_case:o}),async function*(){yield new x.$Y({message:{case:"throw",value:new x.Fu({id:t.id,error:i})}}),yield new x.$Y({message:{case:"streamClose",value:new x.D9({id:t.id})}})}()}static fromResources(e,t){const r=new W(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}async function H(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}}var q=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},z=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 G=(0,C.h)("ExecutorResource"),V=(0,E.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class K{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=q(n,(0,i.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const a=(0,i.mJ)(s),c=a?new x.Kg(a):void 0,l=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new x.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:c,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await H(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)V.increment(s,1,{hook_event_name:t.hookEventName})}};p(d);let f=this.deserializeResult(d);for(;void 0===f;){const e=await H(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),f=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)p(e)}catch(e){G.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),f}catch(e){n.error=e,n.hasError=!0}finally{z(n)}}}class J{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=q(n,(0,i.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,i.mJ)(o),a=s?new x.Kg(s):void 0,c=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new x.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of c){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{z(n)}}}function Z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function X(e,t,r){return{name:e,symbol:Z(e),remoteImplementation:t,registerControlledImplementation:r}}class Q{constructor(e,t){this.resource=e,this.value=t}}function Y(e,t){return[e,t]}function ee(e,t){return t}class te{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new Q(e,t))}get(e){return ee(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class re{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?ee(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 ne(e){return function(t,r){return new x.Ye({id:t,message:{case:e,value:r}})}}function oe(e){return t=>{if(t.message.case===e)return t.message.value}}function se(e){return function(t,r){const n={case:e,value:r};return new x.yT({id:t,message:n})}}function ie(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ae=X("agent-store-conflict-executor",(e=>new K(e,ne("agentStoreConflictArgs"),oe("agentStoreConflictResult"))),((e,t)=>{t.register(new U(e,ie("agentStoreConflictArgs"),se("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class ce{async execute(e,t){return"ack"===t.op?{kind:"acked",count:0}:"release"===t.op?{kind:"released",count:0}:"noteDeferredEagerWrittenPaths"===t.op?{kind:"noted",count:0}:{kind:"not-applicable"}}}X("agent-store-conflict-notice-executor",(e=>new ce),((e,t)=>{}));const le=X("background-shell-executor",(e=>new K(e,ne("backgroundShellSpawnArgs"),oe("backgroundShellSpawnResult"))),((e,t)=>{t.register(new U(e,ie("backgroundShellSpawnArgs"),se("backgroundShellSpawnResult")))})),ue=X("write-background-shell-input-executor",(e=>new K(e,ne("writeShellStdinArgs"),oe("writeShellStdinResult"))),((e,t)=>{t.register(new U(e,ie("writeShellStdinArgs"),se("writeShellStdinResult")))}));function de(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}const he="local";function pe(e,t){return`${e}:task_progress:${t}`}const fe=X("canvas-diagnostics-executor",(e=>new K(e,ne("canvasDiagnosticsArgs"),oe("canvasDiagnosticsResult"))),((e,t)=>{t.register(new U(e,ie("canvasDiagnosticsArgs"),se("canvasDiagnosticsResult")))}));Error;const me=X("computer-use-executor",(e=>new K(e,ne("computerUseArgs"),oe("computerUseResult"))),((e,t)=>{t.register(new U(e,ie("computerUseArgs"),se("computerUseResult")))})),ge=(X("conversation-search-executor",(e=>new K(e,ne("conversationSearchArgs"),oe("conversationSearchResult"))),((e,t)=>{t.register(new U(e,ie("conversationSearchArgs"),se("conversationSearchResult")))})),X("delete-executor",(e=>new K(e,ne("deleteArgs"),oe("deleteResult"))),((e,t)=>{t.register(new U(e,ie("deleteArgs"),se("deleteResult")))}))),we=X("diagnostics-executor",(e=>new K(e,ne("diagnosticsArgs"),oe("diagnosticsResult"))),((e,t)=>{t.register(new U(e,ie("diagnosticsArgs"),se("diagnosticsResult")))}));var ye=r("../context/dist/core.js");(0,ye.cF)(Symbol("execConversationId"),void 0),(0,ye.cF)(Symbol("execRequestId"),void 0),(0,ye.cF)(Symbol("execBrowserOperationSource"),void 0);const ve=X("fetch-executor",(e=>new K(e,ne("fetchArgs"),oe("fetchResult"))),((e,t)=>{t.register(new U(e,ie("fetchArgs"),se("fetchResult")))})),be=X("git-diff-executor",(e=>new K(e,ne("gitDiffRequest"),oe("gitDiffResponse"))),((e,t)=>{t.register(new U(e,ie("gitDiffRequest"),se("gitDiffResponse")))})),Se=X("grep-executor",(e=>new K(e,ne("grepArgs"),oe("grepResult"))),((e,t)=>{t.register(new U(e,ie("grepArgs"),se("grepResult")))})),ke={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"},_e={PreToolUse:ke.preToolUse,PermissionRequest:null,PostToolUse:ke.postToolUse,UserPromptSubmit:ke.beforeSubmitPrompt,Stop:ke.stop,SubagentStop:ke.subagentStop,SessionStart:ke.sessionStart,SessionEnd:ke.sessionEnd,PreCompact:ke.preCompact,Notification:null},Ce=Object.fromEntries(Object.entries(_e).filter((e=>Ee(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Ee(e){return Object.prototype.hasOwnProperty.call(_e,e)}const xe={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Pe=["Glob"],Ie=["Notification","PermissionRequest"],Re=e=>"string"==typeof e,Te=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ae=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$e=(e,t=[])=>({isValid:e,errors:t});function Me(e,t,r){void 0===e||Re(e)||r.push(`${t} must be a string if provided`)}const De={warn:()=>{},info:()=>{}};function Oe(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?{type:"prompt",prompt:e.prompt,...r}:null:e.command?{type:"command",command:e.command,...r}:null}function Fe(e,t,r=De){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=De){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=xe[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Pe.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=Oe(t,o);e&&n.push(e)}return n}function Ne(e,t=De){const r={};for(const[n,o]of Object.entries(e)){if(!Ee(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ie.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=_e[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=Fe(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}}function je(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}const Le="Agent note: Do not suggest workarounds to the blocked tool.";function Ue(e){return e.includes(Le)?e:`${e}\n\n${Le}`}function Be(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 We(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)))}const He=e=>{const t=[];return Te(e)?$e(!0):(t.push("Expected an object"),$e(!1,t))},qe=e=>{const t=[],r=He(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"),$e(0===t.length,t)};function ze(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 Ge=new Set([ke.sessionStart,ke.beforeSubmitPrompt,ke.preToolUse,ke.postToolUse,ke.postToolUseFailure]);function Ve(e){return"prompt"===e.type}function Ke(e){return"command"===e.type||void 0===e.type}const Je={[ke.beforeShellExecution]:qe,[ke.beforeMCPExecution]:qe,[ke.afterShellExecution]:e=>{const t=He(e);return t.isValid,t},[ke.afterMCPExecution]:e=>{const t=He(e);return t.isValid,t},[ke.beforeReadFile]:e=>{const t=[],r=He(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"),$e(0===t.length,t)},[ke.afterFileEdit]:e=>{const t=He(e);return t.isValid,t},[ke.beforeTabFileRead]:e=>{const t=[],r=He(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"),$e(0===t.length,t)},[ke.afterTabFileEdit]:e=>He(e),[ke.beforeSubmitPrompt]:e=>{const t=He(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||Re(e.additional_context)||r.push("additional_context must be a string if provided"),$e(0===r.length,r)},[ke.stop]:e=>{const t=He(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"),$e(0===r.length,r)},[ke.afterAgentResponse]:e=>{const t=He(e);return t.isValid,t},[ke.afterAgentThought]:e=>{const t=He(e);return t.isValid,t},[ke.sessionStart]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Te(e.env))for(const[t,n]of Object.entries(e.env))Re(t)||r.push(`env key "${t}" must be a string`),Re(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||Re(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||Re(e.user_message)||r.push("user_message must be a string if provided"),$e(0===r.length,r)},[ke.sessionEnd]:e=>{const t=He(e);return t.isValid?$e(!0,[]):t},[ke.preCompact]:e=>{const t=He(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $e(!0,[]);const r=[];if(!Ae(e))return r.push("PreCompact response must be an object"),$e(!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"),$e(0===r.length,r)},[ke.subagentStart]:e=>{const t=He(e);if(!t.isValid)return t;if(!Ae(e))return $e(!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||Re(n.user_message)||r.push("user_message must be a string if provided"),$e(0===r.length,r)},[ke.subagentStop]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];return Ae(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$e(0===r.length,r)},[ke.preToolUse]:e=>{const t=[],r=He(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"),Me(e.additional_context,"additional_context",t),$e(0===t.length,t)},[ke.postToolUse]:e=>{const t=[],r=He(e);return r.isValid?(Me(e.additional_context,"additional_context",t),$e(0===t.length,t)):r},[ke.postToolUseFailure]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];return Me(e.additional_context,"additional_context",r),$e(0===r.length,r)},[ke.workspaceOpen]:e=>{const t=He(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")),$e(0===r.length,r)}},Ze=(e,t,r)=>{const n=function(e,t,r){let n;n=e===ke.preToolUse?function(e,t){if(!at(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(!it(t))return r;const n=ct(e);if(!lt(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),at(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===ke.stop?ut(t,r,"Stop"):e===ke.subagentStop?ut(t,r,"SubagentStop"):t;const o=function(e,t,r,n){if(!Ge.has(e)||!at(r)||void 0!==r.additional_context)return r;const o=at(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!it(r))return;const n=Ce[e];if(void 0===n)return;const o=ct(t);return lt(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);return o}(e,t,r),o=(0,Je[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Xe=[ke.beforeShellExecution,ke.beforeMCPExecution,ke.beforeReadFile,ke.beforeTabFileRead,ke.subagentStart,ke.preToolUse],Qe=[ke.workspaceOpen];function Ye(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 et(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function tt(e){return Xe.includes(e)}function rt({step:e,command:t,failClosed:r,kind:n}){const o=tt(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:ot(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function nt(e,t){return t}function ot(e,t){return tt(e)?nt(0,{permission:"deny",user_message:t}):e===ke.beforeSubmitPrompt||e===ke.sessionStart?nt(0,{continue:!1,user_message:t}):e===ke.stop?nt(0,{}):void 0}function st(e){try{return{value:JSON.parse(e)}}catch{return}}function it(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function at(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ct(e){if(!at(e))return;const t=e.hookSpecificOutput;return at(t)?t:void 0}function lt(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function ut(e,t,r){if(!at(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return{...n,followup_message:n.reason.trim()};if(!it(t))return n;const o=ct(e),s=lt(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 dt=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function ht(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;e{const t=[];if(!Te(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)"),$e(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Re(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&&(Re(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)=>{Re(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(Re(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),$e(0===t.length,t)},bt=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$e(!1,r);for(let n=0;n{const t=[];if(!Te(e))return t.push("Hooks config must be an object"),$e(!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"),!Te(e.hooks))return t.push("Config hooks must be an object"),$e(!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(ke),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=bt(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $e(0===t.length,t)};var kt=r("../proto/dist/generated/agent/v1/hooks_pb.js");(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,ye.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,ye.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const _t=(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),Ct=(0,ye.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function Et(e){return"inExecute"!==e.get(Ct).kind}function xt(e,t){const r=e.get(Ct);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}const Pt=X("hook-executor",(e=>new K(e,ne("executeHookArgs"),oe("executeHookResult"))),((e,t)=>{t.register(new U(e,ie("executeHookArgs"),se("executeHookResult")))})),It=new Set(Object.values(ke));function Rt(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function Tt(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function At(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class $t{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return It.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new x.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??"",...ze(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(ke.preCompact,t);return new x.S1({response:new x.w5({response:{case:"preCompact",value:new kt.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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(ke.subagentStart,t);return new x.S1({response:new x.w5({response:{case:"subagentStart",value:new kt.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??"",...ze(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:Rt(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(ke.subagentStop,t);return new x.S1({response:new x.w5({response:{case:"subagentStop",value:new kt.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ke.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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 x.S1({response:new x.w5({response:{case:"beforeSubmitPrompt",value:new kt.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ke.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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 x.S1({response:new x.w5({response:{case:"afterAgentResponse",value:new kt.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ke.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new x.S1({response:new x.w5({response:{case:"afterAgentThought",value:new kt.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ke.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(e),status:Rt(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 x.S1({response:new x.w5({response:{case:"stop",value:new kt.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(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(ke.preToolUse,o);return new x.S1({response:new x.w5({response:{case:"preToolUse",value:new kt.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(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(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(ke.postToolUse,o);return new x.S1({response:new x.w5({response:{case:"postToolUse",value:new kt.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:Tt(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(ke.postToolUseFailure,o);return new x.S1({response:new x.w5({response:{case:"postToolUseFailure",value:new kt.U1({additionalContext:s?.additional_context})}})})}default:return new x.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new x.S1({response:void 0})}}(0,ye.cF)(Symbol("execHookConversationId"),void 0),(0,ye.cF)(Symbol("execHookGenerationId"),void 0),(0,ye.cF)(Symbol("execHookModel"),void 0);const Mt=(0,ye.cF)(Symbol("execHookWorkspaceRoots"),void 0),Dt=X("ls-executor",(e=>new K(e,ne("lsArgs"),oe("lsResult"))),((e,t)=>{t.register(new U(e,ie("lsArgs"),se("lsResult")))})),Ot="cursor-ide-browser",Ft="cursor-dev-control",Nt="custom-user-tools",jt=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Ot,Ft,Nt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Lt(e){return!jt.has(e)}const Ut=new Set([Ft,Ot]);function Bt(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Wt(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 Ht;function qt(e){return void 0===e||void 0===e.serverIdentifiers}function zt(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,ye.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"}(Ht||(Ht={}));const Gt=X("mcp-executor",(e=>new K(e,ne("mcpArgs"),oe("mcpResult"))),((e,t)=>{t.register(new U(e,ie("mcpArgs"),se("mcpResult")))})),Vt=X("list-mcp-resources-executor",(e=>new K(e,ne("listMcpResourcesExecArgs"),oe("listMcpResourcesExecResult"))),((e,t)=>{t.register(new U(e,ie("listMcpResourcesExecArgs"),se("listMcpResourcesExecResult")))})),Kt=X("read-mcp-resource-executor",(e=>new K(e,ne("readMcpResourceExecArgs"),oe("readMcpResourceExecResult"))),((e,t)=>{t.register(new U(e,ie("readMcpResourceExecArgs"),se("readMcpResourceExecResult")))})),Jt=X("mcp-state-executor",(e=>new K(e,ne("mcpStateExecArgs"),oe("mcpStateExecResult"))),((e,t)=>{t.register(new U(e,ie("mcpStateExecArgs"),se("mcpStateExecResult")))})),Zt=X("mcp-allowlist-precheck-executor",(e=>new K(e,ne("mcpAllowlistPrecheckArgs"),oe("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("mcpAllowlistPrecheckArgs"),se("mcpAllowlistPrecheckResult")))}));class Xt extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Qt(e){if(e instanceof Xt)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}const Yt=8388608;var er=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),tr=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function rr(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class cr{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 ar(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new tr.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const lr=X("read-executor",(e=>new K(e,ne("readArgs"),oe("readResult"))),((e,t)=>{t.register(new U(e,ie("readArgs"),se("readResult")))})),ur=X("redacted-read-executor",(e=>new K(e,ne("redactedReadArgs"),oe("redactedReadResult"))),((e,t)=>{t.register(new U(e,ie("redactedReadArgs"),se("redactedReadResult")))})),dr="$file:";const hr=(0,E.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),pr=(0,E.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),fr=(0,E.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"]}),mr=(0,E.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function gr(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${dr}${t}": ${r} A string argument of the form "${dr}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class wr extends Error{constructor(e){super(e.message),this.failure=e}}async function yr(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=>(hr.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new er.iz({result:{case:"error",value:new er.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new wr(gr("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 a=r();if(void 0===a)throw new wr(gr("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,or.xb)(t,(t=>async function(e,t,r,n,o,s){const i=await t.execute(e,new tr.a2({path:r,toolCallId:n,...s?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,n=s&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===n&&"content"!==t.output.case)throw new wr(gr("not_text",r,"the file is not a text file."));if(s&&(fr.increment(e,1,{source:void 0!==n?"vm_digest":"outdated_executor"}),void 0===n))throw new wr(gr("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."));const a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=n??await ar(a??"");if(t.truncated||l>o)throw new wr(gr("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${o} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return{content:a,bytes:l,sha256:c}}case"fileNotFound":throw new wr(gr("not_found",r,"the file does not exist."));case"permissionDenied":throw new wr(gr("permission_denied",r,"reading it was not permitted."));case"rejected":throw new wr(gr("rejected",r,`${i.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":throw new wr(gr("not_text",r,"the file cannot be read as text."));case"error":throw new wr(gr("read_error",r,i.result.value.error));default:throw new wr(gr("read_error",r,"the read returned no result."))}}(e,a,t,n,s,o)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new wr(gr("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 c}(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof wr?e.failure:gr("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(gr("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(dr))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,sr.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,hr.increment(e,1,{route:r,outcome:"expanded"}),pr.record(e,l,{route:r}),mr.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 vr=/\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 br(e,t,r,n){return vr.test(t)?(hr.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${dr}/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 Sr(e){return e.files.map((e=>`"${dr}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class kr{constructor(e,t){this.inner=e,this.getReadExecutor=t}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 yr(e,t,{route:"local",getReadExecutor:this.getReadExecutor});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=br(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 er._Z({content:{case:"text",value:new er.zN({text:Sr(r)})}})):"error"===n.result.case&&(n.result.value.error=br(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const _r=X("mini-swe-agent-bash-executor",(e=>new K(e,ne("miniSweAgentBashArgs"),oe("miniSweAgentBashResult"))),((e,t)=>{t.register(new U(e,ie("miniSweAgentBashArgs"),se("miniSweAgentBashResult")))}));var Cr=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Er=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),xr=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Pr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Ir=X("shell-executor",(e=>new K(e,ne("shellArgs"),oe("shellResult"))),((e,t)=>{t.register(new U(e,ie("shellArgs"),se("shellResult")))})),Rr=X("shell-stream-executor",(e=>new J(e,ne("shellStreamArgs"),oe("shellStream"))),((e,t)=>{t.register(new B(e,ie("shellStreamArgs"),se("shellStream")))})),Tr=((0,ye.cF)(Symbol("optionalPendingPodWrite"),!1),X("write-executor",(e=>new K(e,ne("writeArgs"),oe("writeResult"))),((e,t)=>{t.register(new U(e,ie("writeArgs"),se("writeResult")))})));function Ar(e,t){return new xr.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function $r(e){return{execute:async(t,r)=>new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r.path,error:e,isReadonly:!0})}})}}function Mr(e){return{execute:async(t,r)=>new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function Dr(e){return{execute:async(t,r)=>new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}const Or=X("record-screen-executor",(e=>new K(e,ne("recordScreenArgs"),oe("recordScreenResult"))),((e,t)=>{t.register(new U(e,ie("recordScreenArgs"),se("recordScreenResult")))})),Fr=X("request-context-executor",(e=>new K(e,ne("requestContextArgs"),oe("requestContextResult"))),((e,t)=>{t.register(new U(e,ie("requestContextArgs"),se("requestContextResult")))}));var Nr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const jr=X("shell-allowlist-precheck-executor",(e=>new K(e,ne("shellAllowlistPrecheckArgs"),oe("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("shellAllowlistPrecheckArgs"),se("shellAllowlistPrecheckResult")))})),Lr=X("force-background-shell-executor",(e=>new K(e,ne("forceBackgroundShellArgs"),oe("forceBackgroundShellResult"))),((e,t)=>{t.register(new U(e,ie("forceBackgroundShellArgs"),se("forceBackgroundShellResult")))}));function Ur(e,t){e.hookApprovalRequirement=void 0!==t?new xr.In(t):void 0}function Br(e){return e.hookApprovalRequirement}function Wr(e){return e?.kind===xr.b.FORCE_PROMPT}function Hr(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Wr(e.hookApprovalRequirement))}X("smart-mode-classifier-executor",(e=>new K(e,ne("smartModeClassifierArgs"),oe("smartModeClassifierResult"))),((e,t)=>{t.register(new U(e,ie("smartModeClassifierArgs"),se("smartModeClassifierResult")))}));var qr=r("../proto/dist/generated/agent/v1/agent_pb.js"),zr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Gr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),Vr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Kr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Jr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Zr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Xr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Qr 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 Yr=e=>new qr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Xr.lI({result:{case:"approved",value:new Xr.XJ}})}}),en=(e,t)=>new qr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Xr.lI({result:{case:"rejected",value:new Xr.yc({reason:t??""})}})}}),tn=e=>new qr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Zr.fS({result:{case:"approved",value:new Zr.Hs}})}}),rn=(e,t)=>new qr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Zr.fS({result:{case:"rejected",value:new Zr.m$({reason:t??""})}})}}),nn=(e,t)=>new qr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new qr.zT({result:t})}}),on=e=>new qr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Jr.w$({result:{case:"approved",value:new Jr.q5}})}}),sn=(e,t)=>new qr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Jr.w$({result:{case:"rejected",value:new Jr.rA({reason:t??""})}})}}),an=(e,t)=>new qr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Gr.gz({result:t})}}),cn=(e,t)=>new qr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),ln=(e,t)=>new qr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),un=(e,t)=>new qr.Y5({id:e,result:{case:"prManagementResult",value:t}}),dn=(e,t)=>new qr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Kr.h({result:{case:"rejected",value:new Kr.OI({reason:t??"Authentication was rejected"})}})}}),hn=(e,t)=>new qr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new zr.qG({result:{case:"rejected",value:new zr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),pn=(e,t)=>new qr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Vr.vW({result:{case:"approved",value:new Vr.l3({description:t??""})}})}}),fn=(e,t)=>new qr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Vr.vW({result:{case:"rejected",value:new Vr.Uq({reason:t??""})}})}});var mn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),gn=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,ye.cF)(Symbol("pendingSubagentReplay"),void 0);class wn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const yn=X("subagent-executor",(e=>new K(e,ne("subagentArgs"),oe("subagentResult"))),((e,t)=>{t.register(new U(e,ie("subagentArgs"),se("subagentResult")))})),vn=X("subagent-await-executor",(e=>new K(e,ne("subagentAwaitArgs"),oe("subagentAwaitResult"))),((e,t)=>{t.register(new U(e,ie("subagentAwaitArgs"),se("subagentAwaitResult")))})),bn=X("force-background-subagent-executor",(e=>new K(e,ne("forceBackgroundSubagentArgs"),oe("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new U(e,ie("forceBackgroundSubagentArgs"),se("forceBackgroundSubagentResult")))}));class Sn{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 kn(e){return"string"==typeof e&&e.trim().length>0}const _n=X("web-fetch-allowlist-precheck-executor",(e=>new K(e,ne("webFetchAllowlistPrecheckArgs"),oe("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("webFetchAllowlistPrecheckArgs"),se("webFetchAllowlistPrecheckResult")))})),Cn=e=>e.replace(/[\r\n]/g,"");function En(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":Cn(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":Cn(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":Cn(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const xn="x-inference-authentication-jwt";function Pn(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[xn]:t}}const In={textDelta:(e,t)=>new qr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new qr.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new qr.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new qr.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new qr.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new qr.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new qr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new qr.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new qr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new qr.tr3({thinkingDurationMs:e})}}),thinkingNote:e=>new qr.Uq({message:{case:"thinkingNote",value:new qr.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:In.toolCallDelta(e,new qr.V1v({delta:{case:"taskToolCallDelta",value:new qr.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new qr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new qr.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new qr.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new qr.Uq({message:{case:"tokenDelta",value:new qr.Fyz({tokens:e})}}),summary:e=>new qr.Uq({message:{case:"summary",value:new qr.ECk({summary:e})}}),summaryStarted:()=>new qr.Uq({message:{case:"summaryStarted",value:new qr.lWT}}),heartbeat:()=>new qr.Uq({message:{case:"heartbeat",value:new qr.ih1}}),summaryCompleted:(e,t,r)=>new qr.Uq({message:{case:"summaryCompleted",value:new qr.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new qr.Uq({message:{case:"shellOutputDelta",value:new qr.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new qr.Uq({message:{case:"modelCallCompleted",value:new qr.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 qr.Uq({message:{case:"turnEnded",value:new qr.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 qr.QVp({rawCostCents:r,chargedCents:r,source:qr.nnk.CATALOG})}:{}})}})},stepStarted:e=>new qr.Uq({message:{case:"stepStarted",value:new qr.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new qr.Uq({message:{case:"toolRequestsListed",value:new qr.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new qr.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new qr.Uq({message:{case:"stepCompleted",value:new qr.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new qr.Uq({message:{case:"activeBranchChange",value:new qr.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new qr.Uq({message:{case:"feedbackRequest",value:new qr.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class Rn{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 Tn=r("../agent-kv/dist/index.js");function An(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 $n=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),Mn=r("../utils/dist/fresh-uuid.js"),Dn=r("@connectrpc/connect"),On=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),Fn=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Nn=r("zod/v4");const jn="relayedAttemptFailure",Ln=Nn.object({transport:Nn.boolean(),stallAborted:Nn.boolean(),errorName:Nn.string(),connectCode:Nn.number().optional(),connectCodeName:Nn.string().optional(),connectCause:Nn.object({code:Nn.union([Nn.string(),Nn.number()]).optional(),name:Nn.string().optional()}).optional(),transportFailureKind:Nn.string().optional(),loop:Nn.string().optional(),transportMode:Nn.string().optional()});function Un(e){const t=e?.details?.additionalInfo[jn];if(void 0!==t)try{const e=Ln.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class Bn 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 Wn extends Bn{get kind(){return"RetriableError"}}class Hn extends Bn{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class qn extends Bn{get kind(){return"NonRetriableError"}}class zn extends qn{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 Gn extends Bn{get kind(){return"CancelledError"}}const Vn=new Set([Fn.yM.NOT_LOGGED_IN,Fn.yM.AGENT_REQUIRES_LOGIN,Fn.yM.AUTH_TOKEN_NOT_FOUND,Fn.yM.AUTH_TOKEN_EXPIRED,Fn.yM.INVALID_AUTH_ID,Fn.yM.UNAUTHORIZED,Fn.yM.GITHUB_NO_USER_CREDENTIALS,Fn.yM.GITHUB_USER_NO_ACCESS]),Kn=new Set([Fn.yM.FREE_USER_USAGE_LIMIT,Fn.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Fn.yM.PRO_USER_ONLY,Fn.yM.PRO_USER_USAGE_LIMIT,Fn.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Fn.yM.RATE_LIMITED,Fn.yM.RATE_LIMITED_CHANGEABLE,Fn.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Jn=new Set([Fn.yM.USAGE_PRICING_REQUIRED,Fn.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Zn=new Set([Fn.yM.BAD_API_KEY,Fn.yM.BAD_USER_API_KEY,Fn.yM.OUTDATED_CLIENT]),Xn=new Set([Fn.yM.USER_ABORTED_REQUEST,Fn.yM.DEBOUNCED]),Qn=new Set([Fn.yM.CUSTOM_MESSAGE]),Yn=new Map([[Dn.Code.PermissionDenied,"Permission Denied"]]),eo=["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"],to=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ro=new RegExp(`\\b(${[...to].join("|")})\\b`),no=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],oo="x-cursor-inference-request-error-type",so="AgentWebSocketDeliveryAmbiguousError";function io(e,t={}){const{requestId:r}=t;if(e instanceof Bn)return e;if(ao(e))return function(e,t){const r=lo(e),n=r.code,o=uo(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[jn])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[jn],t.details.equals(new Fn.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:ho(r,oo)??ho(e,oo),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===Un(o)?.transport?{isTransport:!0}:{}};if(n===Dn.Code.Canceled||n===Dn.Code.Aborted)return vo(e)?new Wn(e.message,a):new Gn(e.message,a);if(void 0!==s?.error){const t=s.error;if(Xn.has(t))return new Gn(go(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Hn(go(e,s),r,a);if(void 0!==Po(s))return new Wn(go(e,s),a);if(Vn.has(t))return new Hn(go(e,s),"login",a);if(Kn.has(t))return new Hn(go(e,s),"upgrade",a);if(Jn.has(t))return new Hn(go(e,s),"payment",a);if(Zn.has(t))return new Hn(go(e,s),"config",a);if(Qn.has(t)&&!0!==s.details?.isRetryable)return new qn(go(e,s),a);if(!1===s.details?.isRetryable)return new qn(go(e,s),a)}if(n===Dn.Code.Unauthenticated)return new Hn(e.message,"login",{...a,displayInfo:co(i,"Sign in required",r)});const c=Yn.get(n);return void 0===c||!0===s?.details?.isRetryable||vo(e)?new Wn(e.message,a):new qn(go(e,s),{...a,displayInfo:co(i,c,r)})}(e,r);const n=(0,Tn.y_)(e);if(void 0!==n)return new qn(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===wo)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new qn(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 qn(yo,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:yo,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Gn(e.message,{cause:e,requestId:r});if(e.name===so)return new Wn(e.message,{cause:e,requestId:r,isTransport:!0});if(vo(e))return new Wn(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Wn(s,{cause:e instanceof Error?e:void 0,requestId:r})}function ao(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 co(e,t,r){return{...e,title:e.title||t,detail:e.detail||mo(r),isRetryable:e.isRetryable??!1}}function lo(e){let t=e;for(let e=0;e<10&&t.code===Dn.Code.Unknown;e++){const e=t.cause;if(!ao(e))break;t=e}return t}function uo(e){let t=e;for(let e=0;e<10&&ao(t);e++){try{const e=t.findDetails?.(Fn.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function ho(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 po(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(ao(t))return t;t="cause"in t?t.cause:void 0}}function fo(e){const t=po(e);return void 0===t?void 0:lo(t)}function mo(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function go(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 wo="SummaryPlaceholderRejectedError",yo="Out of disk space. Free some space and try again.";function vo(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(eo.some((t=>e.includes(t)))||ro.test(e))return!0;const n=r.code;if("string"==typeof n&&(eo.some((e=>n.includes(e)))||to.has(n)))return!0;r=r.cause}return!1}function bo(e){return eo.some((t=>e.includes(t)))||ro.test(e)}function So(e){return e instanceof Bn&&e.cause instanceof Error?vo(e.cause):e instanceof Error?vo(e):"string"==typeof e&&bo(e)}function ko(e){return void 0!==e&&e>0}function _o(e){return e+1}function Co(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Eo(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return ko(n)?Co(new Wn("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${_o(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Co(new Wn("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}function xo(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(ao(t)&&(t.code===Dn.Code.Canceled||t.code===Dn.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Po(e){const t=e?.details?.additionalInfo;if(e?.error!==Fn.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 Io=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},Ro=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 To extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ao{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Io(t,(0,i.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,sr.isMessage)(t,x.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const n=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,i.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,i.fU)(n)}else n=e;Io(r,o?new i.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{Ro(r)}})();r.push(n)}await Promise.all(r)}catch(e){if(e instanceof Dn.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new To(e.message);if(e instanceof Dn.ConnectError&&e.code===Dn.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 To(e.message)}else{if(e instanceof P.W2)throw new To(e.message);if(e instanceof Dn.ConnectError&&e.code===Dn.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new To(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ro(t)}}}var $o=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Mo=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Do=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),Oo=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class Fo extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Fo.telemetryName="InteractionListenerStreamClosedError";var No=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 jo=(0,C.h)("ClientInteractionController"),Lo=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Uo{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,i.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=>{jo.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{No(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Lo.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 en(e.id,t);case"webFetchRequestQuery":return rn(e.id,t);case"askQuestionInteractionQuery":return nn(e.id,new $o.tz({result:{case:"rejected",value:new $o.ox({reason:t})}}));case"switchModeRequestQuery":return sn(e.id,t);case"createPlanRequestQuery":return an(e.id,new Gr.bK({result:{case:"error",value:new Gr.iY({error:t})}}));case"setupVmEnvironmentArgs":return cn(e.id,new Oo.r$({result:{case:"success",value:new Oo.JH({})}}));case"replaceEnvArgs":return ln(e.id,new Do.dV({result:{case:"failure",value:new Do.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return un(e.id,new Mo.HL({result:{case:"error",value:new Mo.K$({error:t})}}));case"mcpAuthRequestQuery":return dn(e.id,t);case"connectScmRequestQuery":return hn(e.id,t);case"generateImageRequestQuery":return fn(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 qr.Y5))throw r;return jo.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=>{jo.error(e,"Error handling interaction query",t)})).finally(o)}}async function Bo(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Gn("User aborted request");throw new qn("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new qn("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new qn("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new qr.Ibo({bearerToken:r.bearerToken})}const Wo=15728640,Ho=(0,E.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),qo=(0,E.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),zo=(0,E.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Go(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Vo{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,Tn.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,Tn.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Tn.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Tn.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,Tn.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 Ko({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Go(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(Fr),o=await n.execute(e,new Nr._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),Wo),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 Nr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Nr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Nr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Nr.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,Tn.Bk)(i),(0,Tn.Bk)(a),(0,Tn.Bk)(c),(0,Tn.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Nr.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,Ho.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,Ho.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 Ho.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),qo.histogram(e,m,{mode:o}),zo.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 Jo(e){return Object.keys(e.fileContents).length>0}function Zo(e,t){return Object.assign(new(e.getType()),e,t)}function Xo(e){return Zo(e,{fileContents:{}})}function Qo(e){for(const[t]of e.entries())if(t.symbol===Fr.symbol)return e.get(Fr)}class Yo{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function es(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!==m.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=S(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)=>_.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(S);if(!i.some((e=>k(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&&!!(w(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>k(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 Nr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ts(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function rs(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ts(r)&&ts(n)&&ts(o)&&ts(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,...ts(i)?{dynamicBytes:i}:{}}}const ns=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],os=/\bHTTP (\d{3})\b/;function ss(e){const t=e.message;return"string"==typeof t?t:""}function is(e){return e instanceof Error&&("AbortError"===e.name||e.name===so)}const as={serverCap:3,transportCap:10},cs={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 ls(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function us(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 Bn?e:io(e,{requestId:n});const c=a instanceof Gn&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Xn.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Gn||a instanceof Wn),u="owner"===r.abortOrigin&&a instanceof Wn&&xo(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(ss),o=e=>n.some((t=>t.includes(e))),s=function(e){return fo(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===Dn.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===Dn.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>os.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===Dn.Code.Unknown&&"464"===a?"http_464":i&&s===Dn.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===Dn.Code.DeadlineExceeded&&function(e){const t=po(e);return void 0===t?void 0:uo(t)?.error}(e)===Fn.yM.TIMEOUT?"idle_deadline":i&&s===Dn.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":So(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(is)?"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(Eo(f()),{countAsTransportError:!0});const e=p((()=>Eo(f())),(()=>Eo({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Gn&&!c&&xo(a)&&(a=new Wn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Gn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Hn||a instanceof qn)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!no.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):ls(d);if(a instanceof Gn||a instanceof Hn||a instanceof qn)return h(a);const m=function(e){return Po(e.displayInfo?.errorDetails)}(a);if(a instanceof Wn&&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}}return a instanceof Wn&&(!0===a.isTransport||function(e,t){const r=cs[e];return"by_signature"===r?So(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&xo(a))?p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return ko(n)?new Wn("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${_o(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}}):new Wn("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:"The connection was interrupted. Please check your network connection and try again.",isRetryable:!0,connectCode:o}})}(f())),(()=>a),{immediateFirstRetry:!0}):s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Wn(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${_o(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):ls(d):h(a)}var ds=r("../proto/dist/generated/agent/v1/mcp_pb.js");const hs=(0,C.h)("@anysphere/agent-client:stall-detector"),ps=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,fs={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},ms=(0,E.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),gs=(0,E.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),ws=(0,E.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),ys=(0,E.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class vs{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 bs{constructor(e,t,r){this.lastActivityTime=Date.now(),this.lastMeaningfulActivityTime=Date.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.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.logPrefix=fs[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),ys.increment(this.ctx,1,{loop:this.loop}),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}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=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.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=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=Date.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()}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{if(this.paused)return void(this.timer=setTimeout(e,this.thresholdMs));const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{if(this.paused)return void(this.advisoryTimer=setTimeout(t,e));const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{if(this.paused)return void(this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs));const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(As),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName),this.abortedAt&&(r.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(r.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(r.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const n=[];let o;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:s}=this.activityHistory[e];o!==t&&(o?n.push(`[${t}]`):n.push(`[${t}] (MOST RECENT)`),o=t),n.push(`${r}${s?` (x${s})`:""}`)}return r.activities=n.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=Date.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=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(As);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(hs.warn(this.ctx,a,i),ms.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",loop:this.loop}),this.hasEverStalled||(this.hasEverStalled=!0,ws.increment(this.ctx,1,{loop:this.loop})),this.onStallCallback){const t=Date.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:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs: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?.()}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});hs.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=Date.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),gs.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",loop:this.loop})}[Symbol.dispose](){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=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Ss=(0,ye.cF)(Symbol("agentTransportTimingRecorder"),void 0),ks=(0,C.h)("@anysphere/agent-client:turn-runner"),_s=1e3,Cs=6e4;async function Es(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Gn("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 Gn("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function xs(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 Ps(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Is(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let c=_s;const l=async(r,o,s,i,a)=>{if(s||(c=_s),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&&ks.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Es(n,o)}const l=s?function(e,t){const r=Math.min(3e5,3*e);return t??_s+(r-_s)*Math.random()}(c,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:_s,o=r??Math.min(n*2**e,Cs);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,Cs),n=Math.min(r+.2*r*Math.random(),Cs);return Math.max(e,n)}(l,i.retryAfterMs);u!==l&&e.logging&&ks.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:l,selectedDelayMs:u,endlessRetries:s}),s&&(c=l,e.logging&&ks.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 Es(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let u,d,h,p,f,m=e.state,g=e.action,w=0,y=o,v=0,b=0,S=!1,k=0;const _=()=>{S&&(n.onConnectionStateChange?.({state:"connected"}),S=!1)},C=e=>()=>{e===w&&(f=!0,_())},E=e=>({handleCheckpoint:async(t,n,o)=>{e===w&&(f=!0),await r.handleCheckpoint(t,n,o),e===w&&(u=n,d=o?.resumeEligibility??"eligible",_())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,y);if(u=void 0,d=void 0,f=!1,s.beginAttempt?.({attempt:w,originalRequestId:a}),w>0?(y=(0,Mn.C)(),await(n.onRetryStarting?.(w,{actionCase:g.action.case,conversationState:m,isResume:"resumeAction"===g.action.case,attemptRequestId:y})),e.logging&&ks.info(t,`[${e.logging.tag}] Retrying attempt ${w}`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}),"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&ks.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))):(e.logging&&ks.info(t,`[${e.logging.tag}] Initial request`,{attempt:w,actionCase:g.action.case,requestId:y}),!0===e.notifyInitialResume&&"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&ks.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,y);try{return await s.runAttempt({state:m,action:g,checkpointHandler:E(w),attempt:w,attemptRequestId:y,notifyConnected:_,notifyApplicationProgress:C(w)}),_(),void(e.logging&&ks.info(t,`[${e.logging.tag}] Request successful`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,y);const o=!0===n.endlessRetries?.(),_=e.nowMs?.()??Date.now();f&&(h=void 0,p=void 0);const C=void 0===h?void 0:_-h,E=void 0===p?void 0:_-p;let I=s.classify(r,{attempt:w,attemptRequestId:y,originalRequestId:a,serverErrorRetries:v,transportErrorRetries:b,stallRetryElapsedMs:C,rateLimitRetryElapsedMs:E,endlessRetries:o});if("retry"===I.action){const n="resumeAction"===g.action.case||!0===e.noProgressGuardCountsReplays&&w>0;void 0!==u?k=0:n&&f&&(k++,k>=2&&(e.logging&&ks.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:k,attempt:w,requestId:y,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),I={action:"throw",error:new Wn("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:y,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:I.transportFailureKind}))}const R={...void 0===I.transportFailureKind?{}:{transportFailureKind:I.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},T=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===I.action?`RETRY (countAsServerError=${I.countAsServerError}, countAsTransportError=${I.countAsTransportError})`:`THROW ${I.error.kind}`;ks.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${y} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===I.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:v,transportErrorRetries:b,attempt:w,requestId:y,originalRequestId:a,...R,...T})}if("throw"===I.action){if(0===w){const r={attempt:0,actionCase:g.action.case,error:I.error,requestId:y,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&ks.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:y,originalRequestId:a})}}throw e.logging&&ks.warn(t,`[${e.logging.tag}] Error not retryable`,{...R,...T,attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a,errorName:I.error.name,...!0===e.logging.includeErrorObjects?{error:I.error}:{},serverErrorRetries:v,transportErrorRetries:b}),I.error}const A=w+1;if("ineligible_terminal_turn"===d)return void(e.logging&&ks.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!==I.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:A,trigger:{...R,...s.reconnectTrigger?.(r,I,{originalRequestId:a,failedAttemptRequestId:y,nextAttempt:A})??{originatingRequestId:a,attemptRequestId:y}}}),S=!0),I.countAsServerError&&v++,I.countAsTransportError&&b++,!0===I.stall?h??=_:h=void 0,!0===I.rateLimit?p??=_:p=void 0,w=A,void 0!==u&&(P=u,xs((x=m).turns,P.turns)&&xs(x.rootPromptMessagesJson,P.rootPromptMessagesJson)||(c=_s),m=u,g=new qr.QFf({action:{case:"resumeAction",value:new qr.qKo}})),s.onRetryCommitted?.(),!0===I.immediate||!0===I.noBackoff&&void 0===I.retryAfterMs||await l(w,t.signal,o,I,r)}}var x,P}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var Rs=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},Ts=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 As=(0,ye.cF)(Symbol("agentStreamMetadata"),void 0),$s=(0,C.h)("@anysphere/agent-client:abort"),Ms=(0,C.h)("@anysphere/agent-client:retry"),Ds=(0,C.h)("@anysphere/agent-client:request-context-blob");async function Os({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Go(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Jo(r)&&(t.requestContext=Xo(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Jo(o)&&(e.requestContextParts=Zo(n,{dynamicContext:Xo(o)}))}(t);try{const s=await Ko({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Wo,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?rs(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?rs(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ds.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 Fs=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 Ns(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 js(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,In.shellOutputDelta({case:"stdout",value:new xr.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,In.shellOutputDelta({case:"stderr",value:new xr.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,In.shellOutputDelta({case:"exit",value:new xr.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Ls(e){return e instanceof Error?e.name:void 0}class Us{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,a,c,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new zn(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Qo(e);return void 0===t?e:new re(e,[Y(Fr,{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&&Jo(r)?new Nr._G({result:{case:"success",value:Zo(t,{requestContext:Xo(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new Yo:void 0,y=void 0===w?g:function(e,t){const r=Qo(e);return void 0===r?e:new re(e,[Y(Fr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?es(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Vo(a),S=d.generationUUID??(0,Mn.C)(),k=new Rn,_=(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=po(e);return void 0===t?void 0:Un(uo(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:Ls(e)},r=fo(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=Ls(n);return{...t,underlyingConnectError:{code:r.code,codeName:Dn.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 I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Ms.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=Rs(h,(0,i.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,i.MG)(R.span,(()=>Is({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,...Ps(n)}}},cancellation:{toCancelledError:()=>new Gn("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:a,notifyApplicationProgress:l})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Ms.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Gn("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,d,y,b,c,o,u,v,i,S,k,C,a,l,s,I)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=us(e,function(e,t,r=as){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)&&ns.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 Bn?e:io(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:()=>c.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Ts(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,l,u,d,h,p,f,m,g,w,y,v,b,S="agent.request.attempt"){const k={stack:[],error:void 0,hasError:!1};try{const E=e;e=this.options.prepareAttemptContext?.(e,{attempt:v,attemptRequestId:p,originalRequestId:f,runOptions:h})??e;const I=Rs(k,(0,i.VI)(e.withName(S)),!1);I.span.setAttribute("agent.attempt",v),I.span.setAttribute("agent.request_id",p),I.span.setAttribute("agent.original_request_id",f),e=I.ctx,e=(0,i.Mf)(e,"agent.request_id",p),e=(e=(0,i.Mf)(e,"agent.original_request_id",f)).with(As,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const R=new Set(g.sources);let T=void 0!==g.abortReasonName||void 0!==g.abortReasonMessage;const A=(t,r)=>{if(R.has(t))return;R.add(t),g.sources=[...R];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,g.abortReasonName=n.abortReasonName,g.abortReasonMessage=n.abortReasonMessage),$s.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:p,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",An(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",An(t))}),{once:!0});const[$,M]=e.withCancel();if(l.signal?.aborted){const e=l.signal?.reason;A("conversation_action_abort",An(e)),M()}else l.signal?.addEventListener("abort",(()=>{const e=l.signal?.reason;A("conversation_action_abort",An(e)),M()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Gn("User aborted request")}const D=(0,i.VI)(e.withName("createControlledExecManager")),O=W.fromResources(s);D[Symbol.dispose]();const[F,N]=e.withCancel(),j=new vs,{failThresholdMs:L,advisoryThresholdMs:U}=function(e,t){const r=ps(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=ps(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o{A("stall_detector",{thresholdMs:L,advisoryThresholdMs:U}),N()},onStallCallback:h.onStall,handlerTracker:j}),!1);let H,q;const z=(0,On.Jt)(),G=new P.F8(z,(e=>(B.reset("outbound_write",Fs(e)),e))),V=Rs(k,(0,i.VI)(e.withName("writeInitialRequest")),!1);let K;const J=function(e){return new ds.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?sr.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(d),Z=h.requestContextBlobTransportMode??"legacy",X=0===v&&"userMessageAction"===r.action.case&&0===t.turns.length,Q="ref_only"===Z&&X?"dual":Z,[,Y]=await Promise.all([Os({ctx:e,action:r,resources:s,blobStore:a,options:h,source:"run_request",transportMode:Q,notifyBytes:0===v}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):Bo(h.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:p})]),ee={action:r,headers:h.headers??{}},te=this.options.decorateAttempt?.(ee,h)??ee,re=new qr.Mpn({conversationState:t,action:te.action,modelDetails:n,requestedModel:h.requestedModel,clientLlmGatewayCredential:Y,mcpTools:J,conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:h.subagentModelOverrides??[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,firstProjectOnboarding:h.firstProjectOnboarding,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,emitModelCallUsage:h.emitModelCallUsage,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,transcriptParentConversationId:h.transcriptParentConversationId,runId:f,nextInteractionQueryId:m.peekNext(),voiceCallNotes:h.voiceCallNotes});if(K=G.write(new $n.KS({message:{case:"runRequest",value:re}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),V[Symbol.dispose](),new Gn("User aborted request")}const ne={...te.headers,"x-request-id":p,"x-original-request-id":f,...En(h),...Pn()};H=(0,i.VI)(e.withName("handshakeEstablishment")),H.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=function(e){return e?.get(Ss)}(e)?.startTransportRun(),se=void 0===oe?H.ctx:function(e,t){return e.with(Ss,t)}(H.ctx,oe),ie=0===v&&void 0!==h.onTtftBreakdown?b?.networkPhaseStartedAt:void 0;let ae;const ce=void 0===oe&&void 0===ie?z:(_=z,C=()=>{ae=performance.now(),oe?.markFirstRequestSent(ae)},{[Symbol.asyncIterator](){const e=_[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,C()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),le=this.client.run(se,ce,{signal:F.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===q&&(q=performance.now())}}),ue=performance.now();let de;const he=e=>{H&&(H.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==q&&H.span.setAttribute("handshake.preNetworkMs",q-ue),H[Symbol.dispose](),H=void 0),w();const t=performance.now();de=t,h.onFirstMessage?.(t-ue),void 0!==q&&h.onFirstMessageNetwork?.(t-q)},pe=()=>{y(),h.onFirstNonHeartbeatResponse?.(performance.now()-ue,v)},fe=h.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ie||void 0===ae||"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:ie,transportRunCalledAt:ue,firstRequestTakenAt:ae,firstMessageAt:de??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});h.onTtftBreakdown(void 0===r?e:{...e,transit:r},v)}:void 0,{interactionStream:me,execStream:ge,checkpointStream:we,kvStream:ye,done:ve}=function(e,t,r,n,o,s,i,a){const c=(0,On.Jt)(),l=(0,On.Jt)(),u=(0,On.Jt)(),d=(0,On.Jt)();let h=!1,p=!1;return{interactionStream:c,execStream:l,checkpointStream:u,kvStream:d,done:async function(){let f,m,g=!1,w=!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.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Ms.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(h||(h=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{i?.()}catch(t){Ms.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",Fs(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(g=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await c.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await l.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:o.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===o.message.case&&await d.write(o.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof Bn?e:io(e);return t instanceof Wn&&function(e){return!0===e.isTransport||(e.cause instanceof Error?vo(e.cause):bo(e.message))}(t)}(f)&&(Ms.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)}),r.onStreamEnded(),m=void 0),g||o?.aborted||s?.aborted){if(!g&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${h}`;Ms.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(Ms.warn(e,t),m=new Wn(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(Ms.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new Wn(t,{cause:f,isTransport:!0})):Ms.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Ns(f)})}c.close(),l.close(),u.close(),d.close()}if(void 0!==m)throw m}()}}(e,le,B,he,$.signal,e.signal,pe,fe);let be;const Se={handleCheckpoint:async(e,t,r)=>{await u.handleCheckpoint(e,t,r),be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>u.getLatestCheckpoint()};V[Symbol.dispose]();const ke=5e3;let _e;const Ce=()=>{_e=setTimeout((()=>{G.write(new $n.KS({message:{case:"clientHeartbeat",value:new $n.kA}})).then((()=>B.onClientSentHeartbeat()),(()=>{})),Ce()}),ke)},Ee=()=>{void 0!==_e&&(clearTimeout(_e),_e=void 0)};Ce();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new xr.a({command:n.shellCommand?.command||"",parsingResult:new xr.HO,skipApproval:!0}),a=s.get(Rr).execute(e,i,{execId:n.execId}),c=new Uo(me,o,new P.F8(G,(e=>new $n.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async e=>{await Promise.all([j.track("handleShellStream",js(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Uo(me,o,new P.F8(G,(e=>new $n.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==K&&await Promise.race([K,ve.catch((()=>{}))]);const i=new P.F8(G,(e=>{if((0,sr.isMessage)(e,x.yT))return new $n.KS({message:{case:"execClientMessage",value:e}});if((0,sr.isMessage)(e,x.$Y))return new $n.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,sr.isMessage)(e)?e.getType().typeName:typeof e})`)})),u=new Ao(ge,i,O),v=new Tn.hC(ye,new P.F8(G,(e=>new $n.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),b=new c(we,Se,e);let S,k;const _={promise:new Promise(((e,t)=>{S=e,k=t})),resolve:S,reject:k};$.canceled?(_.resolve(),me.close()):$.signal.addEventListener("abort",(()=>{_.resolve(),me.close()}),{once:!0}),u.run($).then(_.resolve).catch(_.reject);const C=Promise.allSettled([j.track("streamSplitter",ve.finally((()=>{Ee(),l.close(),i.close()}))),j.track("execHandler",_.promise),t.run(e),j.track("checkpointController",b.run()),j.track("kvHandler",v.run(e)),j.track("conversationActionManager",l.run(e,{write:async t=>{await Os({ctx:e,action:t,resources:s,blobStore:a,options:h,source:"queued_action"}),await G.write(new $n.KS({message:{case:"conversationAction",value:t}}))}}))]);let I,R;const T={promise:new Promise(((e,t)=>{I=e,R=t})),resolve:I,reject:R};C.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Gn("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Gn("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?N():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:ve,lingerMs:h.softCancelLingerMs}).then((t=>{Ms.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:p}),N()}))};$.canceled?(A(),T.reject(new Gn("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Gn("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],F=M[1],L=M[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new qn("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===be;if(W){const t={..."rejected"===D.status?{streamSplitter:U(D)}:{},..."rejected"===F.status?{execHandler:U(F)}:{}};Object.keys(t).length>0&&Ms.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!W)throw D.reason;if("rejected"===F.status&&!W)throw F.reason;$.canceled||await this.processUnprocessedMessages(E,l,Se,n,o,s,a,d,h,p,f,m,g,B,w,y)}finally{Ee(),H&&(H[Symbol.dispose](),H=void 0)}}catch(e){k.error=e,k.hasError=!0}finally{Ts(k)}var _,C}async processUnprocessedMessages(e,t,r,n,o,s,i,a,c,l,u,d,h,p,f,m){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),w=r.getLatestCheckpoint();if(!w||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const v=r.getLatestCheckpoint();try{await this.runInternal(e,w,new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:y})}}),n,o,s,i,t,r,a,c,l,u,d,h,f,m,0,void 0,"agent.request.queuedMessage")}catch(e){throw v===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}new RegExp([String.raw`"type"\s*:\s*"response\.(?:output_text|reasoning_summary_text|reasoning_text|function_call_arguments|refusal)\.(?:delta|done)"`,String.raw`"(?:content|reasoning_content|reasoning|refusal)"\s*:\s*"(?!")`,String.raw`"tool_calls"\s*:\s*\[\s*\{`,String.raw`"type"\s*:\s*"content_block_delta"`].join("|"));var Bs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Ws=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const Hs=(0,Dn.createContextKey)(void 0,{description:"anysphere.callerContext"});function qs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function zs(e){return e instanceof Error?e:new Error(String(e))}function Gs(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(zs(e)),t?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:Bs.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 Vs(...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 Ks(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:(a,c,l={})=>{const u=(0,i.fR)(a.withName(`rpc.${String(o)}`),{kind:Ws.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),d=(0,i.fU)(u);let h;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,i.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}(u)),n){const e=n(u);e&&(o=Vs(o,e))}const a=Vs(l.headers,o),{signal:f,cleanup:m}=!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)}}}(u.signal,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,Dn.createContextValues)()).set(Hs,u),w={...l,headers:a,signal:f,contextValues:g},y=s.call(e,c,w);return qs(y)?Gs(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?Promise.resolve(y).then((e=>qs(e)?Gs(e,d,h):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(zs(e)),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(zs(e)),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Js=r("node:crypto?8af2"),Zs=r("../utils/dist/workspace-paths.js");function Xs(){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 Qs(e){return(0,s.join)(Xs(),(0,Zs.r_)(e))}var Ys=r("node:fs/promises"),ei=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),ti=r("node:fs"),ri=r("../shell-exec/dist/api/index.js"),ni=r("./src/agent/native/tree-sitter.webpack.cjs"),oi=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const si=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(oi),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 ni)),ii=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),ai=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function ci(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=>ai.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)ii.has(r.type)&&h(r,t)})(t),ii.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 li(e){return ci(si(),e)}function ui(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function di(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function hi(e,t){const r=di(e,t);return ui(e,r)?r-1:r}function pi(e,t){const r=di(e,t);return ui(e,r)?r+1:r}function fi(e,t){return t>0?e.length<=t?e:e.slice(0,hi(e,t)):""}function mi(e,t){return t>0?e.length<=t?e:e.slice(pi(e,e.length-Math.trunc(t))):""}let gi,wi;function yi(e,t){gi??=new TextEncoder,wi??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,bi.o1)(e);try{return await(0,Ys.realpath)(t)}catch{return t}},_i=1048576,Ci=52428800;var Ei=r("../utils/dist/test-resets.js");const xi="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Pi="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Ii=/\$\(|`|<\(|>\(/,Ri=/[;&|]/;let Ti,Ai,$i,Mi;function Di(){if(void 0===Ti){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ti=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ti}function Oi(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 Fi(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ni(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 ji(){if(void 0===Mi){const e=(process.env[xi]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xi} (expected "allow" or "deny"); using "deny".`);const r=Fi("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Pi]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fi(Pi)),Mi={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fi("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ni("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Mi}function Li(e,t,r={}){const n=[Oi(e),Oi(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 Ui(e,t){const r=function(){const e=ji();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===Ai&&(Ai=Li("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Ai);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Ii.test(e))return r;const s=(void 0===$i&&($i=Li("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$i);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ri.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=ji();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,Ei.J)((function(){Ti=void 0,Ai=void 0,$i=void 0,Mi=void 0}));var Bi=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Wi(e){if(!e)return;let t;return"allow"===e.default?t=Bi.h1.ALLOW:"deny"===e.default&&(t=Bi.h1.DENY),new Bi.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Bi.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Hi(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 Bi.h1.ALLOW:t.default="allow";break;case Bi.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,ri.T6)():(0,ri.Po)())}function qi(e){switch(e){case"system":return Bi.Sz.SYSTEM;case"workspace":return Bi.Sz.WORKSPACE;default:return Bi.Sz.UNSPECIFIED}}function zi(e){const t=function(e){switch(e){case Bi.Sz.SYSTEM:return"system";case Bi.Sz.WORKSPACE:return"workspace";case Bi.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Gi(e){if(!e)return{type:"insecure_none"};switch(e.type){case Bi.vc.INSECURE_NONE:case Bi.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Bi.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Hi(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,...zi(e)};case Bi.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Hi(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...zi(e)};default:return{type:"insecure_none"}}}function Vi(e){if(e)return"insecure_none"===e.type?new Bi.Mw({type:Bi.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Bi.Mw({type:Bi.vc.WORKSPACE_READWRITE,networkAccess:(0,ri.$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:Wi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:qi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Bi.Mw({type:Bi.vc.WORKSPACE_READONLY,networkAccess:(0,ri.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Wi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:qi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Bi.Mw({type:Bi.vc.INSECURE_NONE})}function Ki(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function Ji(e){let t="",r=!1;for(const n of e)Ki(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Zi(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ta={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ra(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ta[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 Ji(t)}function na({rule:e,command:t}){const r=Ji(e).trim();return 0!==r.length&&(null!==function(e){const t=Ji(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Zi(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=Xi(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Zi(e)&&(0===t.length||Zi(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Ji(t).trim(),ra(t).trim()].some((e=>function(e,t){const r=Xi(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(Yi(e,s)&&Yi(n,i))return!0}return e.includes("*")?Yi(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function oa({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=>na({rule:e,command:t}))))return e}function sa(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 ia({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=oa({matchForms:ea({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:sa(n)}var aa=r("../utils/dist/lru-cache.js");const ca=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],la="/Volumes";function ua(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function da(e,t){if("darwin"!==t.platform)return[];const r=ua(e),n=r.toLowerCase(),o=ua(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...ca.map((e=>`${o}/${e}`)),la].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var ha=r("node:util"),pa=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),fa=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function ma(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const ga="utf8",wa="utf8bom",ya="latin1",va={"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 ba(e){return va[e]||e}function Sa(e){return e.startsWith("\ufeff")?e.slice(1):e}function ka(e){const t=e.toLowerCase();return"latin-1"===t?ya:"utf-8"===t?ga:"utf-8-bom"===t||"utf-8 bom"===t?wa:t}function _a(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 Ca=new ha.TextDecoder("utf-8",{fatal:!1}),Ea=new ha.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),xa="�";function Pa(e){return Ca.decode(e)}function Ia(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function Ra(e){let t=0,r=e.indexOf(xa);for(;-1!==r;)t++,r=e.indexOf(xa,r+1);return t}function Ta(e,t){const r=e[t];let n,o=128,s=191;if(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 Aa(e){return e<128?1:e<2048?2:e<65536?3:4}var $a;!function(e){e.CRLF="CRLF",e.LF="LF"}($a||($a={}));const Ma=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Da=new Set(Ma),Oa=new ha.TextDecoder("utf-8",{fatal:!0}),Fa=new ha.TextDecoder("latin1"),Na=Buffer.from([239,187,191]),ja={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},La=8192,Ua="UTF-8",Ba="windows-1252",Wa=/[^\u0000-\u007f\ufffd]/u,Ha=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,qa=/(?:\p{Script=Greek}\p{M}*){3,}/gu,za=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ga=new Map([["windows-1251",Ha],["ISO-8859-5",Ha],["KOI8-R",Ha],["x-mac-cyrillic",Ha],["IBM866",Ha],["IBM855",Ha],["ISO-8859-7",qa],["windows-1253",qa],["windows-1255",za],["ISO-8859-8",za],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Va=/\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,Ka=/[\p{L}\p{M}]+/gu,Ja=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Za=new RegExp(`[A-Za-z]${Ja}{1,2}(?!${Ja})|^${Ja}{1,2}[A-Za-z]`,"u"),Xa=new Map,Qa=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Ma]),Ya=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i,ec=new Set([".ps1",".psm1",".psd1"]),tc=/[^\u0000-\u007f]/u;function rc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function nc(e){const t=rc(e);return Da.has(t)}function oc(e){const t=rc(e);return{encoding:"binary",lineEnding:$a.LF,isBinaryFile:!0,isImageFile:Ya.test(t),isVideoFile:Da.has(t)}}async function sc(e,t){return(await ic(e,t)).text}async function ic(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Ys.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=uc(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=yc(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Sc(n,i),l=Sa(a),u=c===ga&&(d=n).length>=Na.length&&d[0]===Na[0]&&d[1]===Na[1]&&d[2]===Na[2]?wa:c;var d;return vc(e,r,u),o.lineEnding===$a.CRLF?{text:l.replaceAll("\r\n","\n"),encoding:u}:{text:l,encoding:u}}async function ac(e,t){if("binary"===t.encoding)return void wc(e);let r;try{r=await(0,Ys.stat)(e)}catch{return void wc(e)}r.size===t.buffer.byteLength?vc(e,r,t.encoding):wc(e)}async function cc(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await lc(e)}catch{}const r=rc(e);if(Qa.has(r))return oc(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of mc(e)){if(r>=100)break;try{const e=await lc(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:gc()}(t)}catch{return gc()}}(e,r):await lc(e)}catch{const t=rc(e);s=Qa.has(t)?oc(e):gc()}const a=()=>i??=async function(e){try{const t=await(0,Ys.stat)(e);if(!t.isFile()||t.size>Yt)return;return await(0,Ys.readFile)(e)}catch{return}}(e),c=yc(e,await async function(e){try{return await(0,Ys.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ka(o):c?r=ka(c):(r=ka(s.encoding),r!==ga&&r!==wa||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:bc(r).encoding===ya?ya:e}(r,a))),r===ga&&!o&&function(e,t){return"win32"===process.platform&&ec.has(rc(e))&&tc.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Ys.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=wa);const i=r===wa||r===ga&&!o&&await kc(e,Na),u=ja[ba(r)];i?l=Na:u&&await kc(e,u)&&(l=u),s={...s,encoding:i?wa:r}}const u=ma(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=Sa(Sc(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=_a(t),o=_a(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?Sa(t):t,p=s.encoding===wa?ga:s.encoding,f=p===ga?await async function(e,t){if(!t.includes(xa))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(xa)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Ea.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=Aa(o);continue}const s=Ta(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(xa);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:hc(pa.decode(e.subarray(0,La),ba(ka(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(La,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:Ua,lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=Pa(e),s=e.length,Ia(o)||1024*Ra(o)<=s&&!Wa.test(o)))return{encoding:Ua,lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=fa.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ga.get(a);return void 0!==c&&(a=function(e,t,r){const n=ba(ka(t));if(!pa.encodingExists(n))return t;const o=pa.decode(e,n);return Va.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of pa.decode(e,Ba).matchAll(Ka))Za.test(t)&&o++;return o>n}(e,o,r)?Ba:t}(e,a,c)),a!==Ba||function(e,t){const r=ba(ka(t));return!pa.getDecoder(r).write(e).includes(xa)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function dc(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return pc(t,r)}function hc(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return pc(r,t-r)}function pc(e,t){return 0===e&&0===t?$a.LF:e/(e+t)*100>=5?$a.CRLF:$a.LF}async function fc(e){const t=await(0,Ys.open)(e,"r");try{const e=Buffer.allocUnsafe(La),{bytesRead:r}=await t.read(e,0,La,0);return e.subarray(0,r)}finally{await t.close()}}async function*mc(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,Ys.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*mc(r)):n.isFile()&&(yield r)}}catch(e){return}}function gc(){return{encoding:ga,lineEnding:"win32"===process.platform?$a.CRLF:$a.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function wc(e){Xa.delete(e)}function yc(e,t){const r=Xa.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Xa.delete(e)}function vc(e,t,r){if(Xa.has(e)&&Xa.delete(e),Xa.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Xa.size<=100)return;const n=Xa.keys().next().value;void 0!==n&&Xa.delete(n)}function bc(e){try{return{text:Oa.decode(e),encoding:ga}}catch{const t=Pa(e);return Ia(t)?{text:t,encoding:ga}:{text:Fa.decode(e),encoding:ya}}}function Sc(e,t){const r=ka(t);if(r===ga||r===wa||"ascii"===r){const t=bc(e);return r===wa&&t.encoding===ga?{text:t.text,encoding:wa}:t}if(r===ya)return{text:Fa.decode(e),encoding:ya};try{const t=ba(r);if(pa.encodingExists(t))return{text:pa.decode(e,t),encoding:r}}catch{}return bc(e)}async function kc(e,t){try{return(await fc(e)).subarray(0,t.length).equals(t)}catch{return!1}}var _c=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),Cc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class Ec{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Ec.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=uc(t);return r.isBinaryFile?Pa(t):Sa(Sc(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(Rc??=(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,ti.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),Rc),n=(0,s.join)(r,`cursorignore-${Tc(e)}-${Tc(t)}.txt`);if(await Ac(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Ys.writeFile)(i,t,"utf8"),await(0,Ys.rename)(i,n),n}(e,r)}(e,await(0,Ys.readFile)(e));return Pc.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function Mc(e){return Promise.all(e.map((e=>async function(e){const t=Ic.get(e);if(void 0!==t)return t;const r=$c(e).catch((()=>e)).finally((()=>{Ic.delete(e)}));return Ic.set(e,r),r}(e))))}(0,Ei.J)((function(){Pc.clear(),Ic.clear()}));var Dc=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 Oc(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 Fc(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 Mc(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,ri.spawnInSandbox)((0,ri.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=Oc(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 xc.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{Dc(r)}}(),didTimeout:w}}var Nc=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 jc;function Lc({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 Uc{constructor(e=()=>function(e=process.env){if(void 0!==jc)return jc;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}()){this.cache=new Ec({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(Lc(e))}walk(e,t){const r=Lc(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,Oc(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{Nc(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=Fc(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 Bc=[{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 Wc(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map(Bc.map((e=>[e.gitHost,e.apiHost]))),new Map(Bc.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Bc.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Bc.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Bc.map((e=>[e.apiHost,e.gitHost]))),new Map(Bc.map((e=>[e.apiHost,e.internalHost]))),new Map,function(e){const t=Bc.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t}("prod").gitHost;const Hc=new Map;function qc(e){if(void 0===e)return;if(Hc.has(e))return Hc.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||!Wc(t.hostname))return;const r=function(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}`:""}(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 Hc.size>=16384&&Hc.clear(),Hc.set(e,t),t}function zc(e){return void 0!==function(e){const t=qc(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 Gc=new WeakMap;function Vc(e,t,r){const n=performance.now();let o=Gc.get(t);void 0===o&&(o=new Map,Gc.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function Kc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Jc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Xc(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=Zc.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)??Xc(t)??t}}const Zc=new Set(["ftp","file","http","https","ws","wss"]);function Xc(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)}`))}function el(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function tl(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""}const rl=[".gitignore",".cursorignore"],nl=new Map,ol=new Map;function sl(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 il(e){const t=nl.get(e);return void 0!==t?t:sl(nl,2048,e,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())}async function al(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,bi.DN)(e);return null===t?null:t}async function cl(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}(0,Ei.J)((function(){nl.clear(),ol.clear()}));class ll{constructor(e,t,r){this.disposeRequested=!1,this.ignoreServicePromise=hl.init((0,ye.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ignoreServicePromise.then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise.then((e=>{e.dispose()})).catch((()=>{})))}}const ul=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class dl{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=_c().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class hl{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 aa.q({max:2e3}),this.cursorIgnoreCache=new aa.q({max:2e3}),this.gitRootCache=new aa.q({max:1e4}),this.gitRemoteUrlCache=new aa.q({max:200}),this.hasGitDirCache=new aa.q({max:1e3}),this.gitParsedIgnoreCache=new dl(1e4),this.cursorParsedIgnoreCache=new dl(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new aa.q({max:1e4}),this.unwalkedFolders=o.flatMap((e=>da(e,s)))}static getRipwalkCache(){return hl.ripwalkCache??=new Uc,hl.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,bi.DN)(e)??(0,bi.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,bi.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,or.PH)(r,(async e=>{const t=await(0,bi.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=>{const n=await Vc(e,t,r);return null!==n&&da(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([hl.initializeIgnoreMapping(u,".gitignore",c,i),hl.initializeIgnoreMapping(a,".cursorignore",l,i)]),new hl(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,bi.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 hl.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,Ys.access)(n,Ys.default.constants.F_OK);const t=await sc(n),o=hl.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===el(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=hl.deduplicateRootDirectories(e),i=await hl.promiseQueue.enqueueList(o,(e=>hl.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await sc(e),n=hl.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await hl.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,ye.q6)(),o=[],i={root:e,includeGlobs:rl.map((e=>`**/${e}`)),excludeGlobs:[...Qc,...Yc(e,r)],source:"ignore_scan"},a=hl.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}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=hl.parseIgnoreRules(await sc((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)=>_c().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,bi.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,bi.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,bi.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 hl.promiseQueue.enqueueList(o,(e=>hl.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,bi.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,bi.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,bi.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Ys.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const n=e[t];e[t]=n?[...n,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,bi.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()}dispose(){this.gitIgnoreCache=new aa.q({max:1}),this.cursorIgnoreCache=new aa.q({max:1}),this.gitRootCache=new aa.q({max:1}),this.gitRemoteUrlCache=new aa.q({max:1}),this.hasGitDirCache=new aa.q({max:1}),this.directoryWalkPlacementCache=new aa.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await sc(e),n=hl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await sc(e),n=hl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,bi.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,Ys.access)((0,s.join)(e,".git"),Ys.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=await(this.teamSettingsService?.getTeamRepos());if(!t)return!1;const r=t.repos??[],n=t.disableLocalExecAllowlistEnforcement?[]:t.allowedRepos??[];if(0===r.length&&0===n.length)return!1;const o=await this.findGitRootsForFile(e);if(0===o.length)return this.checkNonRepoPathBlockedByAllowlist(e,n);let i=0===n.length,a=!1;for(const t of o){let o;if(this.gitRemoteUrlCache.has(t)?o=this.gitRemoteUrlCache.get(t):(o=await Kc((0,ye.q6)(),this.gitExecutor,t),void 0!==o&&this.gitRemoteUrlCache.set(t,o)),void 0===o)continue;const c=o,l=(0,s.relative)(t,e)||".";for(const e of r)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;n.length>0&&!a&&(a=!0,i=n.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,bi.ZU)({basePath:r,targetPath:e}))return!1;const n=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,n))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,n))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,bi.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,bi.oL)((0,s.relative)(t,e)):(0,bi.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,bi.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){return e.includes("*")?"*"===e.trim()||this.matchRepoUrlGlob(il(e),il(t)):il(e)===il(t)}matchGlob(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=ol.get(e);if(void 0!==t)return t;let r;try{const t=Cc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return sl(ol,2048,e,r)}(r)(t)}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();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=>this.doesRepoUrlMatch(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(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,ye.q6)();for(const e of this.rootDirectories){const o=(0,bi.o1)(e);try{await(0,Ys.access)((0,s.join)(o,".git"),Ys.default.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,s.dirname)(o);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Ys.access)((0,s.join)(i,".git"),Ys.default.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:[...r,...Yc(o,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=hl.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,s.join)(o,e),n=(0,s.dirname)(r),i=(0,s.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Kc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}hl.promiseQueue=new or.TJ({max:ul});const pl="agent-tools",fl=51380224;var ml=r("node:async_hooks");const gl=new ml.AsyncLocalStorage;function wl(e,t){return gl.run(e,t)}new ml.AsyncLocalStorage;var yl=r("../proto/dist/generated/agent/v1/utils_pb.js"),vl=r("../utils/dist/safe-spawn-cwd.js"),bl=r("node:child_process"),Sl=r("../utils/dist/workload-spawn.js");const kl=(0,C.h)("local-exec:shell-output-encoding"),_l=(0,ha.promisify)(bl.execFile),Cl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,El=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function xl(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const Pl="㐀-䶿一-鿿豈-﫿",Il=" -〿㈀-㏿︰-﹯＀-￯",Rl="‐-※←-⇿─-◿★☆",Tl="぀-ヿ",Al=new Map([["cp932",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${Pl}${Il}${Rl}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const $l=function(e){let t,r,n,o=!1,s=0;const i=()=>{s+=1;const e=s;n=async function(){const{stdout:e}=await(0,Sl.D9)(_l,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const s=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=xl(t,Cl),o=xl(t,El);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 pa.encodingExists(t)?t:void 0}(t);return void 0!==n&&Al.has(n)?n:void 0}(s),r=s,o=!0,n=void 0,kl.info((0,ye.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:s.oemcp??"none",acp:s.acp??"none"})}),(t=>{n=void 0,kl.warn((0,ye.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&&i(),{current:()=>("win32"===e&&!o&&void 0===n&&s<3&&i(),t),pages:()=>void 0!==r?r:"win32"!==e||s>=3&&void 0===n?"none":"pending",settled:()=>n??Promise.resolve()}}(process.platform),Ml=Buffer.alloc(0),Dl=/[\u0080-\uffff]/;function Ol(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 Fl(){const e=new xc.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Nl(e,t){return pa.decode(t,e,{stripBOM:!1})}const jl=/[\xe0-\xef][\x80-\xbf]\?/;const Ll=10,Ul=Buffer.alloc(0),Bl=new Set([7,8,9,10,11,12,13,27]);function Wl(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const zl={encoding:"utf8",skip:0};function Gl(e){const t=e();let r="utf8";const n={},o=()=>"utf8"===r?t:n[r]??=ql(r);let s,i=!0,a=Ul,c=!1,l=0;const u=(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?zl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return zl;const n=Hl(e,r);if(-1!==n)return Wl(e,r,n)?{encoding:r,skip:0}:zl;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:Wl(e,r,n)?o:zl}if(-1===i)return t?zl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?zl:void 0;if(0===e[i+1])return o}return zl},d=e=>{if(e===r)return"";const t=o().end();return r=e,t},h=e=>"utf8"===r&&0!==e&&e<128,p=(e,n)=>{let p="",f=e;for(;;){if(i){const e=Math.min(f.length,512-a.length);let r;if(r=a.length>0?Buffer.concat([a,f.subarray(0,e)]):e===f.length?f:f.subarray(0,e),0===r.length)return p;const o=u(r,n||r.length>=512);if(void 0===o)return 1===r.length&&h(r[0])&&(p+=t.write(r),c=!0),a=Buffer.from(r),p;let m=o.skip,g=!1;if(c&&(m="utf8"===o.encoding?1:2,g=r[0]===Ll,c=!1),0===a.length)m>0&&(f=f.subarray(m));else{const t=r.subarray(m);f=f.subarray(e),f=0===f.length?t:0===t.length?f:Buffer.concat([t,f]),a=Ul}if(i=g,l=0,s=void 0,p+=d(o.encoding),g)continue}if(0===f.length)return p;if("utf8"===r&&!f.includes(0)&&!f.includes(254)&&!f.includes(255)){const e=f.lastIndexOf(Ll),r=-1===e?-1:f.length-e-1;if(-1===r||r>=2)return p+t.write(f);if(i=!0,0===r)return e>0&&f[e-1]===Ll&&(a=Buffer.of(Ll),c=!0),p+t.write(f);const n=f[f.length-1];return a=Buffer.of(n),c=h(n),p+t.write(c?f:f.subarray(0,e+1))}const e=Hl(f,r,l,s);if(-1===e)return l+=f.length,s=f[f.length-1],p+o().write(f);p+=o().write(f.subarray(0,e)),f=f.subarray(e),i=!0}};return{write:e=>0===e.length?o().write(e):p(e,!1),peek(){if(!i||0===a.length)return"";const t=u(a,!0);if(void 0===t)return"";const r=c?"utf8"===t.encoding?1:2:t.skip,n=a.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):ql(t.encoding).write(n)},end(){const e=p(Ul,!0)+o().end();return i=!0,a=Ul,c=!1,l=0,s=void 0,e}}}var Vl=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},Kl=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 Jl=(0,C.h)("local-exec:shell-core"),Zl="win32"===process.platform,Xl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Ql(e){return`'${e.replace(/'/g,"'\\''")}'`}const Yl=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function eu(e){return Yl.some((t=>e.includes(t)))?(0,Js.createHash)("sha256").update(e).digest("hex"):e}function tu(e,t){return e[t]??process.env[t]}const ru=/^[A-Za-z_][A-Za-z0-9_]*$/,nu=/CURSOR_SANDBOX/i;function ou(e){return ru.test(e)&&!nu.test(e)}function su(e){return"function"==typeof e?e():e}function iu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function au(e){let t=0,r=0;const n=e.length;for(;rou(e)&&!r.includes(e))),o=`builtin unset ${[...Xl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Xl){const r=tu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Ql(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Ql(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("; ")}(y,b),void 0!==y.__CURSOR_SANDBOX_ENV_RESTORE&&(y.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=eu(e);t!==e&&(r=r.split(e).join(t))}return r}(y.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,S,b.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const k=function(e,t){const r=tu(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[]}}(tu(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=iu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=iu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=iu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=iu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,y),_=(0,ri.CG)(k??ri.BM);let C,E,x;k&&(yield{type:"start",sandboxed:"workspace_readonly"===_||"workspace_readwrite"===_}),t.askpassConfig&&!Zl&&(y.SUDO_ASKPASS=t.askpassConfig.helperPath,y.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,y.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=(this.options.outputFallbackEncoding??(()=>$l.current()))(),I=()=>function(e){if(void 0===e)return Fl();const t=Al.get(e);return void 0!==t&&pa.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=Dl.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&&jl.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Ml,i=0,a="utf8";const c=()=>{a="utf8",o.reset(),i=0},l=(t,n)=>{const s=n?Ol(t):0,c=t.subarray(0,t.length-s),l=c.toString("utf8");if("replacement"!==a){const t=c.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===l.length?"":l[l.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,u=function(e,t,r){let n=Nl(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s{const t=0===s.length?e:Buffer.concat([s,e]);if(s=Ml,"utf8"===a){const e=t.subarray(0,t.length-Ol(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(c(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(l.length))),-1===e?o.note(n):c(),i=u;continue}a="undecided"}const{text:h,keep:p}=l(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&c(),i=u}return r},end:()=>{const e=s;s=Ml;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):l(e,!1).text;return c(),t}}}(e,t):Fl()}(P),R={stdout:Gl(I),stderr:Gl(I)},T=e=>{void 0!==u&&0!==e.length&&(u.file?u.file.write(e):u.buffer+=e)},A=function*(){const e={stdout:f,stderr:m};for(const t of["stdout","stderr"]){const r=R[t].end();0!==r.length&&(void 0!==u&&!0!==u.truncated&&T(r),e[t]||(yield{type:t,data:r}))}};for await(const r of a.execute(e,t.command,{signal:w,workingDirectory:l,env:y,sandboxPolicy:k,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:su(this.options.powershellUtf8Console),powershellUtf8ChildEnv:su(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:su(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:su(this.options.powershellWebRequestUtf8)})){C=0,E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=R[r.type],o="stdout"===r.type?f:m,i=void 0===u||!0===u.truncated;let a=!1;if(!o||!i){C=r.data.length;const c="stdout"===r.type?h:p,l=!o&&c+C<=_i,f=void 0!==u&&!0!==u.truncated&&u.size+C<=fl;"stdout"===r.type?e=l:t=l;const m=!o&&!l,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&T(x),m||(x="")),(l||f)&&(E=n.write(r.data),a=!0),void 0!==u&&u.size+C>fl)u.truncated=!0;else if(f&&void 0!==u)if(u.size+=C,u.lineCount+=au(r.data),u.file)u.file.write(E);else if(u.buffer+=E,u.size>u.threshold){const e=s.default.join(this.projectDir,pl);u.path=s.default.join(e,`${(0,Js.randomUUID)()}.txt`);try{await(0,Ys.mkdir)(e,{recursive:!0}),u.file=(0,ti.createWriteStream)(u.path),u.file.on("error",(e=>{d??=e})),u.file.write(u.buffer)}catch(e){d??=e instanceof Error?e:new Error(String(e)),u.truncated=!0}u.buffer=""}}a||n.end()}switch(r.type){case"stdout":e?(h+=C,E&&(yield{type:"stdout",data:E})):f||(x&&(yield{type:"stdout",data:x}),f=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:ri.Ls});break;case"stderr":t?(p+=C,E&&(yield{type:"stderr",data:E})):m||(x&&(yield{type:"stderr",data:x}),m=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*A();const e=Math.max(0,Math.round(performance.now()-o));let t;if(u?.file){if(u.truncated){const e=`\n... (output truncated at ${u.size} bytes) ...\n`;u.file.write(e),u.size+=e.length,u.lineCount+=ma(e)-1}const e=await new Promise((e=>u.file.end(e)));d??=e??void 0,d?await(0,Ys.rm)(u.path,{force:!0}):t=new yl.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})}d&&void 0!==u?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${u.path}: ${d.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*A()}catch(e){r.error=e,r.hasError=!0}finally{Kl(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 uu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Vl(r,(0,i.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Jl.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{Kl(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class du{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 hu(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(sa(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function pu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return sa(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 fu(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new xr.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new xr.pZ({command:e,workingDirectory:t,reason:pu(r)})}}var mu=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 gu=(0,C.h)("local-exec:background-shell");function wu(e,t,r){return new Cr.Lt({result:fu(e,t,r)})}class yu{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 vu(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 bu(e){e().catch((()=>{}))}class Su{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=vi.L3.compile(e.config.pattern,vi.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=mi(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}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:Date.now()-this.startedAtMs}),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=pe(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:`${fi(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=pe(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&&gu.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 ku{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 Su({shellId:t,outputPath:i,config:o,conversationId:r??he,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&gu.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 _u{async spawn(e,t){const r=new AbortController,n=new yu(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 ri.SandboxUnsupportedError||e instanceof cu)throw e}return bu((()=>vu(n,o))),n}async adopt(e){const t=new yu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,bu((()=>vu(t,e.eventIterator))),t}}function Cu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Eu(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: ${Cu(e.cwd)}\n`,n+=`command: ${Cu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${Cu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function xu(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 Pu{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Ys.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();let g,w="running",y=!1,v=Promise.resolve();const b=async e=>{if(c)try{await c.write(e)}catch(e){}},S=t.shellId,k=s.join(r,`${S}.txt`),_=async()=>{if(!a)return;const e=Date.now()-f,r=Eu({pid:g,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},C=()=>(v=v.then(_).catch((()=>{})),v),E=()=>{void 0!==l&&(clearInterval(l),l=void 0)},x=async e=>{if(p)return;p=!0,g=e;const r=Date.now()-f,n=Eu({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:r});await(0,Ys.writeFile)(k,n,"utf8"),l=setInterval((()=>{C()}),5e3)},P=async()=>{a||(a=await ti.promises.open(k,"r+")),c||(c=await ti.promises.open(k,"a"))},I=async(e,t)=>{if(!y){if(y=!0,E(),p||await x(),await P(),void 0!==t){const e=Date.now()-f,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(r)}w=e,await C()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await x(),await P()),await b(r.data);else if("stderr"===r.type)p||(await x(),await P()),await b(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 x(r.pid),await P());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`;b(`[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 x(),await P(),await b(xu("stderr"));else d=!0,p||await x(),await P(),await b(xu("stdout"));yield r}if(!y){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=Cu(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await v,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,Ys.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let i="running";const a=Date.now()-n,c=Eu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,Ys.writeFile)(r,c,"utf8");const l=await ti.promises.open(r,"r+");let u;try{u=await ti.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=!1,f=!1,m=Promise.resolve();const g=async()=>{const t=Date.now()-n,r=Eu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},w=()=>(m=m.then(g).catch((()=>{})),m);let y=setInterval((()=>{w()}),5e3);const v=()=>{void 0!==y&&(clearInterval(y),y=void 0)},b=async()=>{if(!d){d=!0,v(),await m;try{await l.close()}catch{}try{await u.close()}catch{}}},S=async e=>{try{await u.write(e)}catch(e){}},k=async(t,r)=>{if(!h){if(h=!0,v(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(o)}i=t,await w()}},_={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await S(e.data):"stdout_trimmed"!==e.type||p?"stderr_trimmed"!==e.type||f?"exit"===e.type&&(await k(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await b()):(f=!0,await S(xu("stderr"))):(p=!0,await S(xu("stdout")))}return t.done&&await b(),t}catch(t){const r=e.abortController.signal.aborted;throw await k(r?"aborted":"failed"),await b(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}return await b(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:_})}}class Iu{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:de(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??he,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:Date.now()-o,...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.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},n,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.startTime,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 Ru{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 Tu{constructor(e,t,r,n,o,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new Ru(s,i):s,c=o??function(e){const t=new _u;return new Pu(t,e)}(n),l=new ku(c,n,a);this.backgroundShellManager=new Iu(l,a)}getManager(){return this.backgroundShellManager}dispose(){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,i.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Gi(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=(0,bi.o1)(s),c=new xr.HO(li(n).structured),l=ia({command:n,parsingResult:c,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new Cr.Lt({result:{case:"rejected",value:new xr.pZ({command:n,workingDirectory:a,reason:l})}});let u=o;if(gu.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:c.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Hr(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:c,toolCallId:t.toolCallId},o);if("block"===r.kind)return gu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),wu(n,a,r.reason);gu.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:a,timeout:0,parsingResult:c,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t)},o);if("block"===r.kind)return gu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),wu(n,a,r.reason);u=r.policy,gu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Di()&&(u=Ui(n,c)),u&&"insecure_none"!==u.type){const e=await cl(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}:void 0,s={ctx:e,command:n,workingDirectory:a,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},i=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Cr.Lt({result:{case:"success",value:new Cr.Po({shellId:r,command:n,workingDirectory:a,pid:i.pid})}})}catch(r){if(r instanceof ri.SandboxUnsupportedError){const o=u?.type??"unknown";return gu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Cr.Lt({result:{case:"sandboxUnsupported",value:new xr.rI({command:n,workingDirectory:a,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Cr.Lt({result:{case:"error",value:new Cr.Of({command:n,workingDirectory:a,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{mu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const Au={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},$u=Nn.object({command:Nn.string().optional(),args:Nn.array(Nn.string()).optional(),env:Nn.record(Nn.string(),Nn.string()).optional(),url:Nn.string().optional(),headers:Nn.record(Nn.string(),Nn.string()).optional(),cwd:Nn.string().optional(),envFile:Nn.string().optional(),auth:Nn.object({CLIENT_ID:Nn.string(),CLIENT_SECRET:Nn.string().optional(),scopes:Nn.array(Nn.string()).optional()}).optional(),enabledTools:Nn.array(Nn.string()).optional(),placement:Nn.enum(["server","client"]).optional(),tls:Nn.object({caBundle:Nn.string().trim().min(1).max(131072)}).optional()}),Mu=Nn.object({mcpServers:Nn.record(Nn.string(),$u).optional()}),Du=Nn.enum(["canvas"]),Ou=Nn.array(Du).transform((e=>[...new Set(e)].sort()));class Fu extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Nu(e){const t=e.trim();if(!t)throw new Fu("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Fu("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Fu("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Fu("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 Fu("Missing plugin name before @",e);if(!s)throw new Fu("Missing source after @",e);if(!r.test(o))throw new Fu("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Fu("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 Fu("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 Fu("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 Fu("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new Fu("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 Fu("Missing marketplace name",e);if(!r.test(a))throw new Fu("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function ju(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 Lu(e){return e.sourceInfo.name}function Uu(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Bu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Wu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const Hu=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function qu(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=>Hu.has(e)))}const zu=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Gu=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Vu=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Ku(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Vu.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Ju(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Ju(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Ju(r,t)}else for(const[,r,n,o]of e.matchAll(zu)){const e=r??n;if(void 0===e||Gu.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Zu(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Ju(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:Ku(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.`,...qu(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var Xu=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Qu=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Yu=/^v?(\d+\.\d+(?:\.\d+)?)$/;function ed(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 td(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Yu.exec(e);if(null!==t)return t[1]}}function rd(e){return void 0===e?{kind:"absent"}:Qu.has(e)?{kind:"supported",id:e,version:td(e)??e}:{kind:"unsupported",id:e}}const nd=10485760,od=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,sd=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],id=[".cursor-plugin",".claude-plugin"],ad=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],cd=Nn.object({source:Nn.literal("github"),repo:Nn.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ld=Nn.object({source:Nn.literal("url"),url:Nn.string().url().endsWith(".git","URL must end with .git"),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ud=Nn.object({source:Nn.literal("git-subdir"),url:Nn.string().url().endsWith(".git","URL must end with .git"),path:Nn.string().min(1),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),dd=Nn.union([Nn.string(),cd,ld,ud]),hd=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,pd='Must be a semver version (X.Y.Z) or "never"',fd=Nn.object({cursor:Nn.string().regex(hd,pd).optional(),sand:Nn.string().regex(hd,pd).optional(),sandMobile:Nn.string().regex(hd,pd).optional()}),md=Nn.object({name:Nn.string().min(1,"Author name is required"),email:Nn.string().email().optional()}),gd=Nn.enum(["string","number","integer","boolean","object","array","null"]),wd=Nn.union([gd,Nn.array(gd).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Nn.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function yd(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Nn.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:Nn.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:Nn.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:Nn.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:Nn.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:Nn.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:Nn.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const vd=Nn.lazy((()=>Nn.object({type:wd.optional(),title:Nn.string().optional(),description:Nn.string().optional(),format:Nn.string().optional(),writeOnly:Nn.boolean().optional(),placeholder:Nn.string().optional(),default:Nn.unknown().optional(),enum:Nn.array(Nn.any()).nonempty().optional(),const:Nn.unknown().optional(),properties:Nn.record(Nn.string(),vd).optional(),required:Nn.array(Nn.string()).optional(),additionalProperties:Nn.union([Nn.boolean(),vd]).optional(),items:Nn.union([vd,Nn.array(vd)]).optional(),minLength:Nn.number().int().nonnegative().optional(),maxLength:Nn.number().int().nonnegative().optional(),minimum:Nn.number().optional(),maximum:Nn.number().optional(),exclusiveMinimum:Nn.number().optional(),exclusiveMaximum:Nn.number().optional(),multipleOf:Nn.number().positive().optional(),minItems:Nn.number().int().nonnegative().optional(),maxItems:Nn.number().int().nonnegative().optional(),uniqueItems:Nn.boolean().optional(),minProperties:Nn.number().int().nonnegative().optional(),maxProperties:Nn.number().int().nonnegative().optional()}).strict().superRefine(yd)));function bd(e){const t=vd.superRefine(((e,t)=>{_d(e)&&"object"===e.type||t.addIssue({code:Nn.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?Cd(t.data)?{success:!0,data:t.data}:{success:!1,error:new Nn.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const Sd=Nn.unknown().superRefine(((e,t)=>{const r=bd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!Cd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),kd=(Nn.object({name:Nn.string().min(1).transform((e=>e.toLowerCase())).refine((e=>od.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Nn.string().optional(),source:dd,description:Nn.string().optional(),version:Nn.string().optional(),author:md.optional(),publisher:Nn.string().min(1).optional(),homepage:Nn.string().url().optional(),repository:Nn.string().url().optional(),license:Nn.string().optional(),keywords:Nn.array(Nn.string()).optional(),capabilities:Ou.optional(),logo:Nn.string().optional(),category:Nn.string().optional(),tags:Nn.array(Nn.string()).optional(),minClientVersions:fd.optional(),strict:Nn.boolean().default(!0),commands:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),agents:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),skills:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),rules:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),hooks:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]).optional(),variables:Sd.optional(),mcpServers:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown()),Nn.array(Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]))]).optional()}),Nn.object({description:Nn.string().optional(),version:Nn.string().optional(),pluginRoot:Nn.string().optional()}),Nn.object({name:Nn.string().min(1).regex(od,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Nn.string().optional(),description:Nn.string().optional(),version:Nn.string().optional(),author:md.optional(),publisher:Nn.string().min(1).optional(),homepage:Nn.string().url().optional(),repository:Nn.string().url().optional(),license:Nn.string().optional(),logo:Nn.string().optional(),keywords:Nn.array(Nn.string()).optional(),capabilities:Ou.optional(),minClientVersions:fd.optional(),commands:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),agents:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),skills:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),rules:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),hooks:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]).optional(),variables:Sd.optional(),mcpServers:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown()),Nn.array(Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]))]).optional()}));function _d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cd(e){return _d(e)&&"object"===e.type}function Ed(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function xd(e,t){if(_d(e)&&"string"==typeof e.name){const t=Ed(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Ed(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,Js.randomUUID)()}`}(t)}function Pd(e){if(_d(e)&&_d(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 Id(e){return"string"==typeof e?e:void 0}function Rd(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Td(e){return"string"==typeof e?e:Rd(e)}function Ad(e){if(!_d(e)||!_d(e.metadata))return;const t={description:Id(e.metadata.description),version:Id(e.metadata.version),pluginRoot:Id(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function $d(e){if(!_d(e))return;const t=Id(e.name);if(void 0===t||0===t.length)return;const r=Id(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Md(e){if("string"==typeof e||_d(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||_d(e)));return t.length>0?t:void 0}}function Dd(e){if("string"==typeof e||_d(e))return e}function Od(e){if(void 0===e)return;const t=bd(e);return t.success?t.data:void 0}function Fd(e,t={}){if(e.length>nd)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(!_d(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(!_d(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:_d(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Id(n.ref),sha:Id(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Id(n.ref),sha:Id(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:Id(n.ref),sha:Id(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Id(n.ref),sha:Id(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Id(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?Ed(e.name):"")||function(e){if("string"==typeof e){const t=Ed((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Ed(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Ed((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=Ed((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=Ou.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=fd.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:Id(e.displayName),source:r,description:Id(e.description),version:Id(e.version),author:$d(e.author),publisher:Id(e.publisher),homepage:Id(e.homepage),repository:Id(e.repository),license:Id(e.license),keywords:Rd(e.keywords),logo:Id(e.logo),category:Id(e.category),tags:Rd(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Td(e.commands),agents:Td(e.agents),skills:Td(e.skills),rules:Td(e.rules),hooks:Dd(e.hooks),variables:Od(e.variables),mcpServers:Md(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:xd(r,t),owner:Pd(r),description:Id(r.description),plugins:n,metadata:Ad(r),skippedPluginEntries:o}}}function Nd(e){if(e.length>nd)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=rd(ed(t)),n=kd.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 jd(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 Ld(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Ud(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new Xu.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Bd=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Wd=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Hd=/\$%7B([^%/?#]+?)%7D/gi;function qd(e,t){return zd(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 zd(e,t){if("string"==typeof e)return function(e,t){return e.replace(Hd,"${$1}").replace(Wd,((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=>zd(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]=zd(o,t);return r}return e}function Gd(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Vd=[".mcp.json","mcp.json"],Kd=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Jd(e,t){if(!function(e){return Kd.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 Zd(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Xd(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Vd.map((e=>void 0!==t?`${t}/${e}`:e))}function Qd(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=Gd(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Gd(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?Gd(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Gd(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return qd(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return qd(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 Yd(e,t,r){try{const n=(0,Bd.qg)(e),o=ed(n);if(void 0!==o){const e=r?.log??Au;"unsupported"===rd(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=td(e),n=td(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=Mu.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Qd(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Jd(e,t)&&Zd(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Mu.safeParse({mcpServers:a});if(e.success)return i?e.data:Qd(e.data,t,r)}return null}catch{return null}}function eh(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function th(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Vd,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Yd(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(!Ld(i))return;const a=await t(i);if(null===a)return;const c=Yd(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&eh(s,c.mcpServers,n(i))},a=e=>{const t=Yd(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&eh(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}}}function rh(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}var nh=r("node:stream"),oh=r("node:stream/promises"),sh=r("node:zlib"),ih=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const ah=".cache-complete";function ch(e){return nr(e)}function lh(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function uh(e,t){return function(e,t,r,n){const o=[t,r];return void 0!==n&&o.push(n),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...o):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...o].join("/"):(0,s.join)(e,...o)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?ch(t.version):void 0)}class dh{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return uh(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=lh({parent:t,name:ah});return(await(0,Ys.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,Ys.mkdir)(t,{recursive:!0});const r=nh.Readable.from(e.tarball);return await(0,oh.pipeline)(r,(0,sh.createGunzip)(),(0,ih.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=uh(this.cacheRoot,e);try{return(await(0,Ys.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Ys.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=uh(this.cacheRoot,e);await(0,Ys.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=>ch(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,Ys.writeFile)(lh({parent:t,name:ah}),"")}}function hh(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 ph=[["safe.bareRepository","explicit"]],fh=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],mh=[["core.quotePath","false"]];function gh(e){const t="allow-hooks"===e?fh.filter((([e])=>"core.hooksPath"!==e)):fh;return[...ph,...t]}const wh=(0,ha.promisify)(bl.execFile),yh=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),vh=new Set(["diff","show","blame","log","whatchanged"]);function bh(e){for(let t=0;tArray.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});return Ch("git",[...Eh(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const Ih=/^[0-9a-f]{7,40}$/i,Rh=/^[0-9a-f]{40}$/i;function Th(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 Ah(e,t,r){const n=t.trim();if(Rh.test(n))return{fullSha:n.toLowerCase()};if(Ih.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Ph(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Th(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 Ph(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Th(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 Ph(["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=Th(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const $h=ad.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 Mh;function Dh(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 Oh(e){const t=[];for(const r of e){const e=Dh(r);if(null===e)return"all";t.push(e)}return t}async function Fh(e,t){const r="all"===e?"all":Oh(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Mh??=(async()=>{try{const{stdout:e}=await Ph(["--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}})(),Mh));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...$h,...o])]):[]};var o}function Nh(e){return e.toLowerCase().includes("filtering not recognized by server")}async function jh(e,t,r){await Ph(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Lh(e){try{await(0,Ys.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Ph(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Uh(e,t,r){if("all"!==t&&0===t.length)return;if(!await Lh(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Ph(["sparse-checkout","disable"],n);const o=Oh(t);"all"!==o?await Ph(["sparse-checkout","add","--",...o],n):await Ph(["sparse-checkout","disable"],n)}(0,Ei.J)((function(){Mh=void 0}));const Bh=/\.git$/i,Wh=new Set(["account","dashboard"]);function Hh(e){return e.replace(Bh,"")}function qh(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function zh(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Gh(e){return e.toLowerCase().split(".").includes("gitlab")}function Vh(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function Kh(e){const t=e.toLowerCase();return Gh(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Jh(e){return zh(e)?"github":Gh(e)?"gitlab":Vh(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Zh(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);Wc(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=Hh(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:Jh(r),owner:s.owner,repo:s.repo,host:r}}function Xh(e){const t=Qh(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 Qh(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function Yh(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Zh(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Gh(r.host)){const e=Qh(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=Hh(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=Qh(e.trim());if(null!==t&&Vh(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=qh(t),o=qh(r);if(void 0===n||void 0===o||Wh.has(n.toLowerCase()))return;const s=Hh(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=Qh(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=Hh(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!Wc(e.host)&&null===Kh(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=tp(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Xh(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Kh(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function ep(e){const t=Yh(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 tp(e){return zh(e)?"github.com":e}function rp(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 np(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function op(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}const sp=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 ip(e){const t=nr(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":sp.has(t.toLowerCase())?`_${t}`:t}const ap=18e5,cp=6e5,lp={recursive:!0,force:!0,maxRetries:3},up=["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"],dp=["enotempty: directory not empty, rename","/_staging/"],hp=["upload-pack: not our ref","server does not allow request for unadvertised object"];function pp(e){const t=String(e).toLowerCase().replaceAll("\\","/");return up.some((e=>t.includes(e)))?"user_git_access":dp.every((e=>t.includes(e)))?"local_cache_race":hp.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function fp(e){return"object"==typeof e&&null!==e&&(!0===e.killed||fp(e.cause))}function mp(e){return fp(e)?"killed_by_budget":pp(e)}function gp(e){const t=Yh(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=Zh(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:tp(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const wp=new Map;class yp{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?ap:void 0}localTimeoutMs(){return this.sparsePluginClones?cp:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...xh(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Fh(n?.materialize??"all",this.sparsePluginClones);await Ph(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await jh(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Ph(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Ph(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Nh(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,Js.randomUUID)());return await(0,Ys.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Ys.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Ys.rm)(t,lp),await(0,Ys.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Ys.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,Ys.stat)(n);r-o.mtimeMs>yp.STALE_STAGING_THRESHOLD_MS&&await(0,Ys.rm)(n,lp)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,ip(e),ip(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=gp(e);return(0,s.join)(this.cacheRoot,ip(r),...n.map(ip),ip(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=gp(e);return(0,s.join)(this.cacheRoot,ip(t),...r.map(ip))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=ip(t);try{const e=await(0,Ys.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Ys.rm)((0,s.join)(n,e.name),lp))))}catch{}if(void 0!==r)try{await(0,Ys.rm)(r,lp)}catch{}}async ensureCloned(e,t,r,n=Au,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=Au){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Uh(e,t,{extraGitConfig:xh(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:mp(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:mp(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=(wp.get(r)??Promise.resolve()).catch((()=>{})).then(t);wp.set(r,n);try{return await n}finally{wp.get(r)===n&&wp.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:ep(t);if(null!==a)try{i=(await Ah(a,s,{sshBatchMode:!0,extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&fp(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:pp(e)}),a=null,i=(await Ah(t,s,{extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Ah(t,s,{extraGitConfig:xh(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 Lh(c);return e&&await Uh(c,o,{extraGitConfig:xh(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,Ys.utimes)(l,e,e).catch((()=>{}))}),yp.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&&fp(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:mp(e)}),await(0,Ys.rm)(l,lp),await(0,Ys.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=mp(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,Ys.rm)(l,lp)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Ys.stat)(e)).isDirectory())return!1;const t=await(0,Ys.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Ys.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return op(e,t)}async copyPluginToDir(e,t){await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.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 ad){const n=(0,s.join)(e,r);let o;try{o=await(0,Ys.readFile)(n,"utf-8")}catch{continue}const i=Fd(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=jd(n.source,r.metadata?.pluginRoot);return o&&Ld(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=jd(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":Ld(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):[]}}yp.STALE_STAGING_THRESHOLD_MS=3e5,yp.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const vp=(0,ha.debuglog)("cursor-plugins");function bp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Sp(e){return bp(e)?e:void 0}function kp(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function _p(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 Cp(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Op(e,t.gitUrl)?e:r:e}function Ep(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function xp(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=_p(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Pp="backend-git://";function Ip(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Pp}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Rp(e){if(!e.startsWith(Pp))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 Tp="backend-release://";function Ap(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Tp}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function $p(e){if(!e.startsWith(Tp))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 Mp=/^[0-9a-f]{7,40}$/i;function Dp(e){let t;try{t=gp(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Op(e,t){if(e.trim()===t.trim())return!0;const r=Dp(e),n=Dp(t);return null!==r&&r===n}const Fp=104857600;async function Np(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(!(bp(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>bp(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>Fp)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||!jp(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||!jp(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>Fp)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,Js.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,Ys.mkdir)(n,{recursive:!0});const u=await(0,Ys.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,Ys.writeFile)(d,c),await(0,Ys.mkdir)(h,{recursive:!0});let e=0,t=0;await ih.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,Ys.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,Ys.readdir)(e)).some((e=>id.includes(e)))&&(a=e)}const p=await(0,Ys.readdir)(a);await Promise.all(p.map((e=>(0,Ys.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Ys.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function jp(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Lp{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??Au,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new yp(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=xh(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:ep(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 Ah(e,t,n):await Ah(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&fp(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}};for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=_p(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=kp({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;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,Js.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:Sp(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=Cp(c,r),d=xp(e,o),h=hh(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?Ap({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Ip(g,d,t.gitPath??void 0);const w=Ep(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Op(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:Ip(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:Sp(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}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=Rp(e.downloadUrl);return!(!r||!Op(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Ys.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Ys.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${nr(t.name)}.md`,o=[];o.push(`description: ${np(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${np(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Ys.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,Ys.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${nr(t.name)}.md`,o=t.description?`---\ndescription: ${np(t.description)}\n---\n\n`:"";await(0,Ys.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,Ys.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&rp(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,Ys.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,Ys.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,Ys.mkdir)(c,{recursive:!0}),await(0,Ys.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,Ys.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===$p(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)&&fp(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=Au,n,i){const a=i?.sparsePluginClones??!1,c=a?ap:void 0,l=$p(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Np(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=op(r,e.gitPath);await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Ys.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Np(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Rp(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Au,o,s="all",i=!1){const a=performance.now(),c=Mp.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?ap:void 0,h=i?cp:void 0,{sparse:p,sparseDirs:f}=await Fh(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await jh(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Ph(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Ph(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Ph(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Ph(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Ph(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Ph(["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:ep(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&fp(t))throw t;await(0,Ys.rm)(r,{recursive:!0,force:!0}),await(0,Ys.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Nh(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);vp("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?Oh([u.gitPath]):[],a),u.gitPath)o=op(d,u.gitPath);else{const t=await async function(e,t){for(const r of ad){const n=(0,s.join)(e,r);let o;try{o=await(0,Ys.readFile)(n,"utf-8")}catch{continue}const i=Fd(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=jd(c.source,a.metadata?.pluginRoot);return l&&Ld(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 Uh(d,Oh([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=op(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 Uh(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Ys.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,xh(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=Oh(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?Oh([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,Oh([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 Up(e,t,r,n,o){return new Lp(e,t,r,n,o)}var Bp=r("node:url"),Wp=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Hp=()=>({});function qp(e,t){return Wp(e,{...t,engines:{...t?.engines,js:Hp,javascript:Hp}})}function zp(e,t,r){return Wp.stringify({content:e,data:{}},t,r)}function Gp(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Vp(e,t){if(Object.hasOwn(e,t))return e[t]}function Kp(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?Gp(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===Vp(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Gp(t.projectPath)===a&&!0===Vp(i,e))))),r||!0!==Vp(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 Jp=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");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=Jp.Ay.load(t[1],{schema:Jp.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=Vd.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(!Ld(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(!Ld(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(!Ld(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=>th(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:Zu(a??i),configs:l}}}function af(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cf(e){return!!af(e)&&(void 0===e.enabledPlugins||af(e.enabledPlugins))}function lf(e){return JSON.parse(e)}function uf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function df(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=lf(await(0,Ys.readFile)(n,"utf-8"));cf(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=lf(await(0,Ys.readFile)(o,"utf-8"));cf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}async function hf(e){try{return(await(0,Ys.lstat)(e)).isSymbolicLink()}catch{return!1}}async function pf(e){if(await hf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Ys.readFile)(e,"utf-8")}async function ff(e){if((await(0,Ys.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function mf(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 gf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Ys.realpath)(e),n=op(t,r),o=await(0,Ys.realpath)(n);if(op(t,o),!(await(0,Ys.stat)(o)).isFile())return;return await ff(o),(0,Bp.pathToFileURL)(o).href}catch{return}}function wf(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 yf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function vf(e,t){return wf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function bf(e,t,r){let n;for(const o of sd){const i=(0,s.join)(e,o);let a;try{if(await hf(i))continue;if(!(await(0,Ys.stat)(i)).isFile())continue;await ff(i),a=await pf(i)}catch{continue}const c=Nd(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 gf({installPath:e,logo:l.logo}),S=wf(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&&!yf(S))continue;if(!g&&!C){n=n?{...n,fields:vf(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=vf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||yf(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 Sf(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,Ys.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return op(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,Ys.realpath)(t);try{return op(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,Ys.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,Ys.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 ff(i);const l=await(0,Ys.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,Ys.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([kf(r,o.skills,e),Cf(r,o.agents,e),Ef(r,o.commands,e),_f(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function kf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Pf({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}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=Pf({content:Gd(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Cf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=If({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Ef(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function xf(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 Pf({content:e,relativePath:t}){try{const r=qp(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:xf(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function If({content:e,relativePath:t}){try{const n=qp(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 Rf({content:e,relativePath:t}){try{const r=qp(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 Tf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Af(e,t,r){const n=r??Tf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of sd){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=ed(a);const c=Nd(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return th(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ld(t))return null;const r=(0,s.join)(e,t);try{return await hf(r)?null:(await(0,Ys.stat)(r)).isFile()?(await ff(r),await pf(r)):null}catch{return null}}}(e),{fallbackFileNames:Xd(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function $f(e,t,r){const n=await Af(e,void 0,{log:r});if(n)return n;for(const n of ad){const o=(0,s.join)(e,n);try{if(!(await(0,Ys.stat)(o)).isFile())continue;const n=await(0,Ys.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Of(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Ff),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(!Ld(n))continue;const o=(0,s.join)(e,n);try{await ff(o);const t=Yd(await pf(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 Mf=new Set(Object.values(ke));function Df(e){return Mf.has(e)}function Of(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ff(e){return!(!Of(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Nf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Df(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Gd(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Gd(e.prompt,t)}:e)));return{...e,hooks:r}}async function jf(e,t,r,n){if("object"==typeof r){const o=Lf(r,t);return o&&"config"in o?{config:Nf(o.config,e),...void 0!==n&&{sourcePath:n}}:o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Ld(t))return;o=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else o=(0,s.join)(e,"hooks","hooks.json");try{if(await hf(o))return;if(!(await(0,Ys.stat)(o)).isFile())return}catch{return}try{await ff(o),i=await(0,Ys.readFile)(o,"utf-8")}catch{return}try{a=JSON.parse(i)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const c=Lf(a,t);return c&&"config"in c?{config:Nf(c.config,e),sourcePath:o}:c}function Lf(e,t){const r=function(e){if(!Ae(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(Ae(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"===r){const r=St(e);return r.isValid&&St(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===r){if(!(Of(n=e)&&Of(n.hooks)&&Object.keys(n.hooks).length>0))return;const r=Ne(e.hooks),o=St(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}var n}async function Uf(e,t,r,n){const o=n?.log??Au,s=await bf(e,t,o),i={...Tf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Sf(e,s?.manifestOptions),Af(e,r,i),jf(e,t,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 Bf(e,t,r){const n=r?.log??Au,o=await bf(e,t.raw,n),[s,i,a]=await Promise.all([Sf(e,o?.manifestOptions),$f(e,t,n),jf(e,t.raw,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 Wf(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 Uf(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 Hf(e,t,r={}){const n=r.log??Au,o=performance.now(),i=await async function(e){const t=uf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=lf(await(0,Ys.readFile)(r,"utf-8"));return af(n=e)&&af(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=uf(e),r=(0,s.join)(t,"settings.json");try{const e=lf(await(0,Ys.readFile)(r,"utf-8"));return cf(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 Kp(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=Kp(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 df(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=Nu(e),s=await Bf(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(Nu(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}async function qf(e){const t=e.log??Au,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new dh(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))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,Ys.mkdir)(o,{recursive:!0});try{await n.installPlugin(e,o),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,Ys.rm)(o,{recursive:!0,force:!0})}catch{}throw e}s=o}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await Wf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const n=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:n.message,errorType:mf(n)});const o=e.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:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:o,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,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 zf(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 Gf(e){return zf(e)??`path:${e.installPath}`}function Vf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Kf(e,t){const r=[];for(const o of e){const e=ju(o.identifier),i=`plugin:${e}`,a=Lu(o.identifier),c=Uu(o.identifier),l=Bu(o.identifier),u=Wu(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}(0,s.join)((0,o.homedir)(),".claude","plugins","marketplaces");const Jf=Nn.object({path:Nn.string(),name:Nn.string().optional(),description:Nn.string().optional(),globs:Nn.array(Nn.string()).optional(),alwaysApply:Nn.boolean().optional(),content:Nn.string(),environments:Nn.array(Nn.string()).optional(),disabledEnvironments:Nn.array(Nn.string()).optional()}),Zf=Jf.extend({name:Nn.string()}),Xf=Nn.object({path:Nn.string(),name:Nn.string(),description:Nn.string().optional(),tools:Nn.array(Nn.string()).optional(),model:Nn.string().optional(),prompt:Nn.string(),permissionMode:Nn.enum(["default","readonly"]).optional()}),Qf=Nn.object({path:Nn.string(),name:Nn.string(),description:Nn.string().optional(),argumentHint:Nn.string().optional(),content:Nn.string()}),Yf=Nn.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),em=Nn.object({config:Yf,sourcePath:Nn.string().optional()}),tm=Nn.custom((e=>"object"==typeof e&&null!==e));function rm(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}}Nn.object({schemaVersion:Nn.number().int(),displayName:Nn.string().optional(),description:Nn.string().optional(),authorName:Nn.string().optional(),skills:Nn.array(Jf),rules:Nn.array(Zf),agents:Nn.array(Xf),commands:Nn.array(Qf),mcpConfig:Mu.extend({mcpServerSourcePaths:Nn.record(Nn.string(),Nn.string()).optional()}).optional(),hooks:em.optional(),hooksError:Nn.string().optional(),capabilities:Nn.array(Nn.string()),variablesSchema:tm.optional()}),Error;class nm extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function om(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sm(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function im(e){try{return sm(await(0,Ys.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 am(e){const t=await im(e);return void 0===t?[]:function(e){const t=function(e){const t=sm(e);if(0===t.trim().length)return{};const r=[],n=(0,Bd.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Bd._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new nm(`.cursor/settings.json contains syntax errors: ${e}`)}if(!om(n))return{};const o=n.plugins;if(void 0===o)return{};if(!om(o))return{};const s={};for(const[e,t]of Object.entries(o))om(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||rm(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function cm(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,ha.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,Js.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,Ys.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 Im=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 Rm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Rm(e)}[/\\\\]${Rm(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 Uc,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,i.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),a=(0,s.resolve)(this.userHomeDirectory);if(o===a||da(o,{platform:process.platform,homeDirectory:a}).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 Vc(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 c=this.getThirdPartyExtensibilityEnabled(),l=this.buildIncludeGlobs(c),u={root:this.root,includeGlobs:l,excludeGlobs:Qc,followSymlinks:!0,source:"nested_extensibility"},d={rules:[],skills:[],markdown:[],agents:[]},h=Om.getRipwalkCache();try{const e=h.walk(r.ctx,u);try{for await(const t of e.lines){const e=Dm(t,c);e&&d[e].push((0,s.resolve)(this.root,t))}}finally{h.delete(u)}}catch{}return r.span.setAttribute("nested_extensibility.rules",d.rules.length),r.span.setAttribute("nested_extensibility.skills",d.skills.length),r.span.setAttribute("nested_extensibility.markdown",d.markdown.length),r.span.setAttribute("nested_extensibility.agents",d.agents.length),d}catch(e){t.error=e,t.hasError=!0}finally{Im(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,Ys.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,Ys.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Ys.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,Ys.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 jm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Lm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=Lm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Lm(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,C.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 sc(e)}catch(t){return{skillFilePath:e,error:u(t)}}try{return{skillFilePath:e,content:t,parsed:qp(t)}}catch(t){return{skillFilePath:e,error:d(t)}}}async function Zm(e){const t=await ki(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 fi(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---`:zp("",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 ${f(s.length)} characters; the limit is 64. Rename the skill's folder.`),p.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 ${f(i)} characters; the limit is ${f(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${f(a)} tokens; the recommended limit is ${f(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 m.DX({fullPath:e,content:t,frontmatter:n,type:new m.f5({type:{case:"global",value:new m.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=h(s,og(r));return i?new m.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new m.f5({type:{case:"agentFetched",value:new m.Xo}})}):new m.DX({fullPath:e,content:t,frontmatter:n,type:new m.f5({type:{case:"agentFetched",value:new m.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=xf(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:h(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 m.DX({fullPath:e,parseError:t,type:new m.f5({type:{case:"agentFetched",value:new m.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,ha.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 m.i9};else{const r=xf(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new m.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new m.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new m._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 m.DX({fullPath:e.path,content:e.body,type:new m.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,i.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ha.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,a,c,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=a,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),a),this.ignoreService=l??new ll(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ha.debuglog)("Failed to load cursor rules:",e),[]))),c){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=c.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,ye.q6)(),n=Hm(t,(0,i.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,ha.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new Uc,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(w((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,ha.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 w(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Vc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=b(await sc(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else 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,i.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),a=await Vc(n.ctx,this.gitExecutor,o)||o,c=this.loadCursorRulesRule(n.ctx,a).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([c,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);const f=[...p.values()];return(await async function(e){const t=e.filter((e=>w((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,Ys.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ki(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=>!w((0,s.basename)(e.fullPath))||i.has(e)))}(f.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,i.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Ys.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await sc(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,i.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,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let a=t;const c=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(a,".cursor","rules"),t=a;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];c&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,a,e));const i=(0,s.dirname)(a);if(i===a)break;a=i}const l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}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,i.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,Ys.stat)(e)).isFile()){const t=y({content:await sc(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 al((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,i.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=b(await sc(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,i.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){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=gg.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,s.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Ys.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}class wg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[]){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.getEnabledSkills=p,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,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 f=performance.now();let m=!1,g=!1,w=!1;const y=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-f),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:m})}catch{}return t})).catch((e=>(g=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=y;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(w=!0,this._loaded!==t?this._loaded:(g&&this.closeSeedWindow(e),void 0===r?y:(m=!0,r)))));this.seededLoaded=t,this._loaded=t,y.then((r=>{this._loaded===t?g?w&&this.closeSeedWindow(e):(this._loaded=y,m&&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=>m.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,ye.q6)(),n=Hm(t,(0,i.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,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(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,i.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(o,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(o,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,t))))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([o]));if(this.isIgnoredSkillPath(o)||this.isPrunedByExtensibilityScan(o))return r;const s=t.get(o);if(void 0===s){try{await(0,Ys.stat)(o)}catch{return r}return await this.loadAll(n.ctx)}let i;try{i=await(0,Ys.realpath)(o)}catch{return await this.loadAll(n.ctx)}if(i!==s)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await sc(e);return{skillFilePath:e,content:t,parsed:qp(t)}}(o),realSkillFilePath:i},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=c,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,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(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,i.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],s=[],a=new Map,c=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),l=new Set(this.getAgentStoreSkillRoots()),u=await Promise.all(this.foldersToWatch.filter((e=>!l.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),d=new Set;for(const e of u)for(const t of e)if(!d.has(t.realSkillFilePath))if(d.add(t.realSkillFilePath),"error"in t)a.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;a.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const h=(await c).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),p=await Promise.all(h.map((e=>ki(e)))),f=[];for(const[e,t]of h.entries()){const r=p[e];d.has(r)||(d.add(r),f.push(t))}const m=await Promise.all(f.map((e=>Zm(e))));for(const e of m)if("error"in e)a.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;a.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:a}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function yg(e){let t;switch(e.type){case"global":t=new m.f5({type:{case:"global",value:new m.i9}});break;case"fileGlobbed":t=new m.f5({type:{case:"fileGlobbed",value:new m.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new m.f5({type:{case:"agentFetched",value:new m.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new m.f5({type:{case:"manuallyAttached",value:new m._u}});break;default:e.type,t=new m.f5({type:{case:"manuallyAttached",value:new m._u}})}return new m.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 vg{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,ha.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=>(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,i.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],a=[];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 Kf(e,(e=>e.skills))}(e),i=function(e){return Kf(e,(e=>e.rules))}(e);for(const e of[...r,...i])o.push(yg(e));for(const t of e){const e=`plugin:${ju(t.identifier)}`,r=Lu(t.identifier),n=Uu(t.identifier),o=Bu(t.identifier),i=Wu(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===qp(c.content).data?.["disable-model-invocation"]}catch{}a.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:i,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",a.length),{rules:o,agentSkills:a}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}const bg=(0,ha.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()?gn.b$.READONLY:gn.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 Nm({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,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,Ys.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await sc(r));if(!o)continue;t.push(new gn.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 Ig=new Set(["claude-code-tutor"]);class Rg{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)Ig.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=Lu(n.identifier),o=Uu(n.identifier),i=Bu(n.identifier),a=Wu(n.identifier);for(const c of n.agents){const l=Vf(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?gn.b$.READONLY:gn.b$.DEFAULT;t.push(new gn.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}}var Ag=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const $g=bl.execFile;function Mg(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,Sl.D9)($g,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ag.w3.UNSPECIFIED,Ag.w3.LEFT,Ag.w3.MIDDLE,Ag.w3.RIGHT,Ag.w3.BACK,Ag.w3.FORWARD,Ag.Dh.UNSPECIFIED,Ag.Dh.UP,Ag.Dh.DOWN,Ag.Dh.LEFT,Ag.Dh.RIGHT;const Dg=(0,ha.promisify)(bl.execFile);function Og(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 Fg(e){const{stdout:t}=await(0,Sl.D9)(Dg,"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:Og(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ag.w3.UNSPECIFIED,Ag.w3.LEFT,Ag.w3.MIDDLE,Ag.w3.RIGHT,Ag.w3.BACK,Ag.w3.FORWARD,Ag.Dh.UNSPECIFIED,Ag.Dh.UP,Ag.Dh.DOWN,Ag.Dh.LEFT,Ag.Dh.RIGHT;const Ng={pattern:"[\\w-]{1,64}",next:e=>e},jg={pattern:"[0-9a-f-]{36}",next:()=>Js.randomUUID()},Lg={pattern:"webp",next:()=>"webp"},Ug={native:[jg,Lg],agent:[Ng,jg,Lg],legacyNative:[jg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Ug).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Ng.pattern}$`),Ag.Z8.NATIVE_X11,Ag.Z8.XDOTOOL,(0,E.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,E.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,E.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,E.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,C.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,E.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Bg=r("../proto/dist/runtime/compact.js");Bg.HL;var Wg=(0,Bg.QT)(sr.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);sr.proto3,sr.proto3,sr.proto3,sr.proto3;class Hg{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:Wg.ARROW,arrow:Wg.ARROW,default:Wg.ARROW,top_left_arrow:Wg.ARROW,hand:Wg.POINTER,hand1:Wg.POINTER,hand2:Wg.POINTER,pointer:Wg.POINTER,pointing_hand:Wg.POINTER,xterm:Wg.TEXT,ibeam:Wg.TEXT,text:Wg.TEXT,watch:Wg.WAIT,wait:Wg.WAIT,progress:Wg.WAIT,left_ptr_watch:Wg.WAIT,crosshair:Wg.CROSSHAIR,cross:Wg.CROSSHAIR,tcross:Wg.CROSSHAIR,move:Wg.MOVE,fleur:Wg.MOVE,size_all:Wg.MOVE,sb_v_double_arrow:Wg.RESIZE_NS,v_double_arrow:Wg.RESIZE_NS,ns_resize:Wg.RESIZE_NS,row_resize:Wg.RESIZE_NS,top_side:Wg.RESIZE_NS,bottom_side:Wg.RESIZE_NS,sb_h_double_arrow:Wg.RESIZE_EW,h_double_arrow:Wg.RESIZE_EW,ew_resize:Wg.RESIZE_EW,col_resize:Wg.RESIZE_EW,left_side:Wg.RESIZE_EW,right_side:Wg.RESIZE_EW,top_left_corner:Wg.RESIZE_NWSE,bottom_right_corner:Wg.RESIZE_NWSE,nwse_resize:Wg.RESIZE_NWSE,size_fdiag:Wg.RESIZE_NWSE,top_right_corner:Wg.RESIZE_NESW,bottom_left_corner:Wg.RESIZE_NESW,nesw_resize:Wg.RESIZE_NESW,size_bdiag:Wg.RESIZE_NESW,not_allowed:Wg.NOT_ALLOWED,no_drop:Wg.NOT_ALLOWED,forbidden:Wg.NOT_ALLOWED,circle:Wg.NOT_ALLOWED,grab:Wg.GRAB,openhand:Wg.GRAB,grabbing:Wg.GRABBING,closedhand:Wg.GRABBING};class zg{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 Hg(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=Wg.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 Mg("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 Mg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return qg[t]??Wg.ARROW}try{const e=await Mg("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 Wg.ARROW}catch{return Wg.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,C.h)("computer-use-lazy");var Gg=r("node:net");function Vg(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 Kg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Jg=Nn.object({rpcSocketPath:Nn.string().min(1).optional(),appControlSocketPath:Nn.string().min(1).optional(),pid:Nn.number().int().positive().optional().catch(void 0),protocolMajor:Nn.number().int().positive().optional().catch(void 0)}).passthrough(),Zg=Nn.object({data:Nn.string(),mimeType:Nn.string().min(1)}).strip(),Xg=Nn.object({message:Nn.string(),screenshot:Zg.optional(),screenshotBefore:Zg.optional(),structuredContent:Nn.unknown().optional(),isError:Nn.boolean()}).strip(),Qg=Nn.object({accessibilityTrusted:Nn.boolean(),screenRecordingGranted:Nn.boolean()}).strip(),Yg=Nn.union([Nn.object({id:Nn.number().int(),result:Xg,ok:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),sessionId:Nn.string().min(1),ok:Nn.literal(!0).optional(),result:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),ok:Nn.literal(!0),result:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int().nullable().optional(),error:Nn.string().min(1),errorCode:Nn.string().min(1).optional(),result:Nn.never().optional(),ok:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),permissionStatus:Qg,result:Nn.never().optional(),ok:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),sessionId:Nn.never().optional()}).strip()]);function ew(e,t){try{return JSON.parse(e)}catch{throw new Kg(`local-cua ${t} is not valid JSON`)}}const tw={responseMaxBytes:33554432,parseServiceState(e){const t=Jg.safeParse(ew(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Kg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Yg.safeParse(ew(e.toString("utf8"),"RPC response"));if(!r.success)throw new Kg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Kg("local-cua RPC response ID did not match");return r.data}};class rw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function nw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Vg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const ow=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),sw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class iw{constructor(e){this.mode=e}static isInstalled(){if((0,ti.existsSync)(iw.serviceExecutablePath()))return!0;let e;try{e=tw.parseServiceState((0,ti.readFileSync)(iw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||iw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await iw.readServiceState(),t=e?.pid;return void 0!==t&&iw.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!==iw.protocolMajor&&void 0!==e.pid&&!iw.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;iw.throwIfAborted(e.signal);const t=(0,Js.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:iw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw iw.rpcError(r);if(void 0===r.sessionId)throw new rw("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 iw.readServiceState();if(void 0===e)return;const r=await iw.sendOnce(iw.socketPathFrom(e),{id:iw.requestID,method:"control/release",requestID:(0,Js.randomUUID)(),mode:this.mode,sessionId:t},iw.defaultCallTimeoutMs);if(void 0!==r.error)throw iw.rpcError(r)}catch(t){iw.logger.warn(e,"local-cua control release failed",{error:nw(t)})}}}async callTool(e,t,r){iw.throwIfAborted(e.signal);const n=iw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:iw.requestID,method:"tools/call",requestID:(0,Js.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 iw.rpcError(o,t);const s=o.result;if(void 0===s)throw new rw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new rw(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=iw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);iw.throwIfAborted(e.signal);try{return await iw.sendOnce(o,t(),n,e.signal)}catch(o){if(!iw.isPreDeliveryConnectionError(o))throw o;iw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:iw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return iw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await iw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new rw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(iw.throwIfAborted(e.signal),!t){const e=await iw.readServiceState();if(e&&!iw.isExitedIncompatibleHelper(e))return iw.socketPathFrom(e)}await this.launchAndWait(e);const r=await iw.readServiceState();if(!r)throw new rw("local-cua sidecar did not publish service.json after launch");return iw.socketPathFrom(r)}static setLaunchGuard(e){iw.launchGuard=e}async launchAndWait(e){const t=iw.serviceAppPath(),r=iw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){iw.logger.info(e,"launching local-cua sidecar",iw.sidecarLaunchLogFields(t)),"1"===process.env[iw.directLaunchEnv]?await iw.spawnSidecarProcess(e,iw.serviceExecutablePath(),[],{detached:!0}):await iw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+iw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...iw.sharedInstallRelativePath,`${iw.serviceAppBundleName}.app`)}static helperIdentity(){const e=iw.serviceAppPath(),t=process.env[iw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=iw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,ti.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&&sw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??iw.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:ow.get(i.bundleIdentifier))??iw.appSupportFolder)};return(0,ti.existsSync)(a)&&(iw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${iw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,Js.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[iw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return nw(e)}static socketError(e){const t=nw(e);return new rw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return iw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,bl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new rw(`local-cua sidecar launch failed: ${iw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{iw.logger.warn(e,"local-cua sidecar process error after launch",{error:iw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Ys.readFile)(iw.serviceStatePath(),"utf8");return tw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Kg)return;throw new rw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==iw.protocolMajor)throw new rw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${iw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new rw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw iw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(iw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Gg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new rw("local-cua RPC aborted"):iw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new rw(`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(iw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>tw.responseMaxBytes)return void d((()=>s(new rw("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=tw.parseResponse({line:n,expectedID:iw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new rw("local-cua RPC connection failed after request delivery")):()=>s(iw.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 rw(e))))})))}))}}let aw;function cw(){if(void 0===aw){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 aw===e&&(aw=void 0),t}));aw=e}return aw}iw.logger=(0,C.h)("local-cua:rpc"),iw.serviceAppBundleName="Cursor Computer Use",iw.appSupportFolder="cursor-computer-use",iw.productionExecutableName="CUCursorService",iw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],iw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",iw.serviceAppOverrideEnv="CUA_SERVICE_APP",iw.directLaunchEnv="CUA_DIRECT_LAUNCH",iw.protocolMajor=1,iw.defaultCallTimeoutMs=45e3,iw.launchReadyTimeoutMs=8e3,iw.launchPollIntervalMs=200,iw.requestID=1;var lw=r("node:module");const uw="mac-webp-runtime.cjs";function dw(e){return"function"==typeof e}function hw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function pw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(hw):[]}let fw,mw;function gw(){return fw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=pw()[0]?.getFileName();return function(){const e=lw;if("createRequire"in e&&dw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&dw(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}})(),fw}function ww(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(mw??=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 pw()){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,Bp.fileURLToPath)(n):n);r((0,s.join)(t,uw)),r((0,s.join)(t,"..","..","src","computer-use",uw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),uw)),r((0,s.join)(process.cwd(),"src","computer-use",uw)),r((0,s.join)(process.cwd(),"computer-use",uw));try{const e=(0,s.dirname)(gw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",uw)),r((0,s.join)(e,"dist","computer-use",uw))}catch{}for(const t of e)try{const e=gw()(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")}(),mw)}function yw(...e){return t=["@jsquash","webp",...e].join("/"),gw().resolve(t);var t}async function vw(...e){var t;return await(t=(0,Bp.pathToFileURL)(yw(...e)).href,ww()(t))}const bw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Sw=(bw((async()=>{const e=await vw("decode.js");return await e.init({wasmBinary:await ti.promises.readFile(yw("codec","dec","webp_dec.wasm"))}),e})),bw((async()=>{const[e,t,r]=await Promise.all([vw("utils.js"),vw("meta.js"),vw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await ti.promises.readFile(yw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),kw="image/png",_w={async normalize(e){if(e.mimeType!==kw)throw new Error(`Mac screenshot must be ${kw}, received ${e.mimeType}`);const t=await cw(),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 Sw(),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}},Cw={userFacing:function(e){if(e instanceof rw&&e.userFacing&&e.message.trim().length>0&&!Vg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof rw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Ew=new Set(["keys"]),xw=new Set(["matched","mismatch","unchecked"]),Pw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Iw=new Set(["matched"]),Rw=new Set(["too_long"]),Tw=new Set(["watched","fell_back","unavailable","over_budget"]);class Aw{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??Cw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Aw.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:Aw.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:Aw.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:Aw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Aw.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:Aw.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===Ag.EB.DOWN||t.value.stroke===Ag.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 Ag.ks({result:{case:"success",value:new Ag.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=Aw.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=Aw.cursorFromResult(e)??Aw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Aw.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",xw),a=o("unchecked",Pw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Iw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Rw.has(a);return new Ag.qA({method:o("method",Ew)??"",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",Tw)})}async errorResult(e){let t;if(Aw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:nw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Aw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:nw(e)})}const r=this.errors.userFacing(e);return new Ag.ks({result:{case:"error",value:new Ag.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 Ag.ks({result:{case:"error",value:new Ag.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ag.ks({result:{case:"error",value:new Ag.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Aw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Aw.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=nw(r);return Aw.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 Ag.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 Ag.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()}))}}Aw.logger=(0,C.h)("local-cua:actions"),Aw.mouseButtonNames={[Ag.w3.UNSPECIFIED]:"left",[Ag.w3.LEFT]:"left",[Ag.w3.RIGHT]:"right",[Ag.w3.MIDDLE]:"middle",[Ag.w3.BACK]:"left",[Ag.w3.FORWARD]:"left"},Aw.scrollDirectionNames={[Ag.Dh.UNSPECIFIED]:"down",[Ag.Dh.UP]:"up",[Ag.Dh.DOWN]:"down",[Ag.Dh.LEFT]:"left",[Ag.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,C.h)("local-cua:windows");var $w;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"]),function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}($w||($w={}));var Mw=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 Dw{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}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,i.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Er.Pi({result:{case:"error",value:new Er.GU({path:n,error:Si})}});const o=(0,bi.o1)(n,this.workspacePath),a=await this.permissionsService.shouldBlockWrite(e,o,"");if(a){const e=await hu(a,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Er.Pi({result:{case:"rejected",value:new Er.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const c=await async function(e,t){const r=await(0,Ys.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Ys.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,bi.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),l=await this.pendingDecisionProvider.requestApproval({type:$w.Delete,details:{path:c},toolCallId:t.toolCallId});if(!l.approved)return new Er.Pi({result:{case:"rejected",value:new Er.iq({path:o,reason:l.reason||""})}});let u;try{u=await(0,Ys.stat)(o)}catch(e){return"ENOENT"===el(e)?new Er.Pi({result:{case:"fileNotFound",value:new Er.n0({path:o})}}):new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:tl(e)})}})}if(!u.isFile()){const e=u.isDirectory()?"directory":"other";return new Er.Pi({result:{case:"notFile",value:new Er.LX({path:o,actualType:e})}})}const d=u.size;let h;if(d<=Ci)try{h=await sc(o)}catch{}const p=h??"",f=await(0,Ys.stat)(o).catch((()=>{}));if(f?.dev!==u.dev||f.ino!==u.ino)return new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Ys.unlink)(o)}catch(e){return"EACCES"===el(e)?new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===el(e)?new Er.Pi({result:{case:"fileBusy",value:new Er.vX({path:o})}}):new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:tl(e)})}})}if(this.fileChangeTracker&&void 0!==h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(o,h,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Er.Pi({result:{case:"success",value:new Er.fl({path:o,deletedFile:o,fileSize:BigInt(d),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Mw(r)}}}class Ow{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===Nt));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 ds.I0({serverIdentifier:Nt,serverName:Nt,instructions:`User-defined tools for this session (server "${Nt}"). 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 Fw extends Ow{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Nw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),jw=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 Lw{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,i.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new Nw.uN({result:{case:"success",value:new Nw.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Nw.uN({result:{case:"error",value:new Nw.fk({url:n,error:tl(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{jw(r)}}}class Uw{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){const o=this.changes.get(e);if(o){const t=o.before,s=n||o.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:s};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}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,Ys.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 cc(e,t,r,n);await(0,Ys.writeFile)(e,o),await ac(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()}}class Bw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const Ww=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),Hw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],qw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,zw=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Gw=new Set(["system","global","command"]),Vw={GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",GIT_SSH_COMMAND:"ssh -o BatchMode=yes",GCM_INTERACTIVE:"Never",GIT_EDITOR:":",GIT_SEQUENCE_EDITOR:":",GIT_OPTIONAL_LOCKS:"0",GIT_LFS_SKIP_SMUDGE:"1",GIT_CONFIG:void 0};function Kw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const Jw=Kw([...gh("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 Zw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Xw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function Qw(){const e=new Map;return{async exec(t,r,n){const o=Zw(n);return Ch("git",await Yw(e,t,r,o),{cwd:t,env:Vw,windowsHide:!0,killSignal:"SIGTERM",timeout:Xw(o)})},async run(t,r,n){const o=Zw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=kh(t);return(0,bl.spawn)("git",s,{...o,env:_h(s,n)})}(0,t,{cwd:e,env:Vw,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"})))}),Xw(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 Yw(e,t,r,o),o,n?.input)}}}async function Yw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=kh(e),r=bh(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=Ww.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=[...Hw,..."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),...Jw],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 Ch("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Vw,windowsHide:!0,killSignal:"SIGTERM",timeout:Xw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Bw("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 Bw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Bw("read-failed",t)}(e)}if(performance.now()>=r)throw new Bw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Bw("read-failed");const r=new Set;for(let e=0;eKw([[`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 ey(e,t,r){return Qw().exec(e,t,r)}var ty=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 ry{async exec(e,t,r,n){return ny(e,t,r,n,ey)}forRequest(){const e=Qw();return{exec:(t,r,n,o)=>ny(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function ny(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,i.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:a,stderr:c}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:a,stderr:c}}catch(e){s.error=e,s.hasError=!0}finally{ty(s)}}var oy=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class sy{constructor(){this.lineEnd=0,this.nextStart=0}}function iy(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 cy=-(2**31),ly=2**31-1;function uy(e){return Number.isNaN(e)?0:ely?ly:e}function dy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return uy(Math.trunc(e))}var hy=r("../mcp-core/dist/transport/mcp-url-utils.js");function py(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function fy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function my(e,t,r){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){return!0===e.url?.startsWith("mcp-provider://")}(e))return!0;const n=t.allowedMcpServers??[];return 0===n.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){const n=r?.matchesServerUrlPattern??hy.vc;return t.some((t=>{const r=py(t.command),o=fy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,hy.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t,r)}(e,n,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){const n=r?.matchesServerUrlPattern??hy.vc;return(t??[]).some((t=>{const r=py(t.command),o=fy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,hy.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t.deniedMcpServers,r)}var gy=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 wy extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class yy extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class vy extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class by{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new wy(t);return await o(e,r)}}class Sy{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,i.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new yy(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{gy(s)}}}class ky{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,Js.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,Ys.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,Ys.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Ys.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var _y=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},Cy=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 Ey{async load(e,t,r,n,o){const s=o(e,r);return new Py(e,t,s,r)}}function xy(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Py{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,i.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=_y(t,(0,i.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=_y(s,(0,i.VI)(e.withName("CachedMcpClient.callTool")),!1),c=await this.getClient(a.ctx);if(null===c)throw new Error("Client is not ready");return c.callTool(a.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{Cy(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=_y(r,(0,i.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{Cy(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=_y(n,(0,i.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{Cy(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function Iy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ry(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 Ty(e){return e?` (${Ry(e,"")})`:""}function Ay(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=Ay(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=Ay(n);if(void 0===e)return;r[t]=e}return r}function $y(e){const t=Ay(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const My=new TextDecoder("utf-8",{fatal:!0});function Dy(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function Oy(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=My.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=Dy(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: ${Ry(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const Fy=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function Ny(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function jy(e){if(!Iy(e))return;const t=e.resource;return Iy(t)&&void 0===Ny(t)&&"string"==typeof t.blob&&Fy.has(Dy(t.mimeType))?t.blob:void 0}function Ly(e){const t=e,r=t.resource;if(Iy(r)){const e=Ny(r);return void 0!==e?e:"string"==typeof r.blob?Oy(r,r.blob).text:`Resource: ${Ry(r.uri,"unknown")}${Ty(r.name)}`}return t.uri?`Resource: ${Ry(t.uri,"unknown")}${Ty(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function Uy(e){const t=$y(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var By=r("zod/v4-mini");const Wy=By.object({CLIENT_ID:By.string(),CLIENT_SECRET:By.optional(By.string()),scopes:By.optional(By.array(By.string()))}),Hy=By.strictObject({caBundle:By.string().check(By.trim(),By.minLength(1),By.maxLength(131072))}),qy=By.object({type:By.optional(By.literal("stdio")),command:By.string(),args:By.optional(By.array(By.string())),env:By.optional(By.record(By.string(),By.string())),envFile:By.optional(By.string()),cwd:By.optional(By.string()),enabledTools:By.optional(By.array(By.string())),startupTimeoutSec:By.catch(By.optional(By.number().check(By.positive())),void 0)}),zy=By.object({type:By.optional(By.enum(["http","sse"])),url:By.string(),headers:By.optional(By.record(By.string(),By.string())),auth:By.optional(Wy),tls:By.optional(Hy),placement:By.optional(By.enum(["server","client"])),enabledTools:By.optional(By.array(By.string()))}),Gy=By.union([qy,zy]),Vy=By.object({mcpServers:By.record(By.string(),Gy)});Error;const Ky=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Jy(e,t){if("string"==typeof e)return function(e,t){return e.replace(Ky,((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=>Jy(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Jy(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 Zy(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const Xy=Zy({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),Qy=Zy({caBundle:"ca_bundle"}),Yy=Zy({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),ev=Zy({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),tv=(new Map([["auth",{keys:Xy,unknownKeyIsError:!1}],["tls",{keys:Qy,unknownKeyIsError:!0}]]),"enabled");new Set([...Yy.jsonKeyOf.keys(),...ev.jsonKeyOf.keys(),tv]);Symbol("disabled");const rv=(0,C.h)("McpConfig");async function nv(e,t=e=>process.env[e]){try{const r=await(0,Ys.readFile)(e,"utf8"),n=Jy((0,Bd.qg)(r),t);return Vy.parse(n)}catch{return{mcpServers:{}}}}async function ov(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function sv(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await ov(0,t);return n.length>0&&rv.warn((0,ye.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 iv=["enterprise","project","user","env"];function av(e){return"project"===e||"env"===e}const cv=["0.0.0.0/0","::/0"];function lv(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,hy.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function uv(e){const t=!0===e.enabled,r=lv(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...cv];const t=lv(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...cv]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...cv];const r=(0,hy.b6)(e);return r.includes("*")?[...cv]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class dv 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 hv=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class pv extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class fv 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 mv(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function gv(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&&hv.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(!mv(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 fv;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 fv;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 pv;return e(i,a)}}function wv(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)&&xv(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=bv(e,n),s=Cv(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:bv(e,"cause"),l=Cv(c,t,r),u=e instanceof AggregateError?bv(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>Cv(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])=>vv(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(kv(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[Sv];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=Rv(e);return void 0!==g&&Rv(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 yv(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 vv(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function bv(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const Sv=Symbol.for("nodejs.util.inspect.custom");function kv(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 _v(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return wv(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>_v(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:_v(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function Cv(e,t,r){if(e instanceof Error)return wv(e,t,r);try{return xv(e,t)?_v(e,t,1,r):e}catch{return}}const Ev=4096;function xv(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=Ev||n.length>Ev)return Pv(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((Iv(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(bv(s,"message"),bv(s,"stack"),bv(s,"cause")),s instanceof AggregateError&&n.push(bv(s,"errors")));for(const e of Object.keys(s))n.push(bv(s,e))}}return!1}function Pv(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,bv(n,e)]))),message:bv(n,"message"),stack:bv(n,"stack"),cause:bv(n,"cause"),...n instanceof AggregateError?{errors:bv(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function Iv(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 Rv(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const Tv=/spt_[A-Za-z0-9_]{6,}/g,Av=/[A-Z0-9]/;function $v(e){return function(e){return e.replace(Tv,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&Av.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var Mv=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set([1,2]);const Dv="cursor/requiresConfirmation",Ov="https://grok.com/connectors-oauth-exchange-code/",Fv="https://x.com/i/connectors/oauth_callback",Nv="https://chat.x.com/connectors/oauth_callback",jv="https://lite.x.com/i/connectors/oauth_callback",Lv={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},Uv={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Ov,Fv]},Bv="x-cursor-auth";function Wv(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 Hv="https://mcp.shop.com",qv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},zv=new Map([["mcp.slack.com",{gate:"mcp_oauth_scope_step_up",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/}]]),Gv=new Map([["gmailmcp.googleapis.com",{...Lv,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",{...Lv,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Lv,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",{...Lv,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Lv,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Lv,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Lv,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",Uv],["mcp.money-staging.x.com",Uv],["mcp.money.x.com",Uv],["connectors-gateway.grok.gcp.mouseion.dev",qv],["connectors-gateway.grok.com",qv],["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.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","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:Hv}}]]),Vv=[".cloud.databricks.com",".azuredatabricks.net",".gcp.databricks.com"];const Kv=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Jv={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Zv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0};function Xv(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(".."))&&Vv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Jv:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Kv.test(e.pathname.replace(/\/+$/,""))}(t)?Zv:(r=t.hostname,Gv.get(r.toLowerCase()));var r}function Qv(e){return e.endsWith("/")?e:`${e}/`}async function Yv(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Qv(r.pathname).startsWith(Qv(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const eb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function tb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function rb(e,t){if(void 0===t)return;const r=new URL(e),n=tb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!eb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function nb(e){const t=tb(e);return void 0===t?void 0:zv.get(t.hostname.toLowerCase())}const ob=new Set([...Gv].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),sb="https://www.cursor.com/bot/mcp/oauth/callback",ib={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:sb},ab="tailnet_";new Set([`${ab}waiting_for_approval`,`${ab}tailnet_locked`,`${ab}joining`]);const cb="grokbot://mcp/oauth/callback",lb="http://localhost:8787/callback",ub="gb";new Set(["outlook","outlook-calendar","onedrive","teams"]),new Set(["teams"]);function db(e){const t=new URL(lb);return t.port=String(e),t.toString()}function hb(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 pb(e){const t=e.redirectUrl??lb;if(!0!==e.loopbackIpv4||!hb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function fb(e,t=ib){const r=new Set,n=void 0!==e&&hb(e);return e&&!n&&r.add(e),r.add(t.portal),e===cb&&r.add(t.grokBotBounce),r.add(lb),e&&n&&r.add(e),Array.from(r)}new Map([[ub,cb],["gw",Ov],["gd",lb],["xa",Fv],["xc",Nv],["xl",jv],...[18787,28787,31787].map((e=>[`gd${e}`,db(e)]))]),new Map([[cb,ub],[sb,ub],[Ov,"gw"],[Fv,"xa"],[Nv,"xc"],[jv,"xl"]]),pb({loopbackIpv4:!0}),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const mb=new Set([429,502,503,504]);function gb(e){return"object"==typeof e&&null!==e}function wb(e){const t=gb(e)?e.code:void 0,r=(e instanceof Error||gb(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&&mb.has(o)&&!mb.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}const yb=8192;function vb(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Wv(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const bb=/\$\{[^}]*\}/;function Sb(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&bb.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const kb=new Map;async function _b(e,t=fetch){if(void 0===Wv(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=kb.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 kb.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Ei.J)((function(){kb.clear()}));const Cb={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function Eb(e){return Cb}const xb=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Pb=["invalid_request","invalid_token","insufficient_scope"];function Ib(e){return Pb.some((t=>t===e))}function Rb(e){const t=[];for(const r of e){if(t.length>=20)break;r.length>0&&r.length<=200&&xb.test(r)&&!t.includes(r)&&t.push(r)}return t}const Tb=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,Ab=/"((?:[^"\\]|\\.)*)"?/y,$b=/[^\s,]*/y;function Mb(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 Fb(e){if("object"!=typeof e||null===e||Array.isArray(e))return Db;const t=Ob("grantedScopes"in e?e.grantedScopes:void 0),r=Ob("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:Ob("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:Ob("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Nb(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function jb(e,t){return e.filter((e=>!t.has(e)))}const Lb={stepUpScopes:[],recordRequestedScopes:async()=>{}};function Ub(e){const t=nb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=Eb(e.accountKey);let o;const s=async()=>Fb(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Nb(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=Mb(t,"error")?.toLowerCase(),n=Mb(t,"resource_metadata");return{error:void 0===r||""===r?"none":Ib(r)?r:"other",scopes:Rb((Mb(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 ob.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl)||!await e.isEnabled())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 Rb(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(){if(!await e.isEnabled())return Lb;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:Nb(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Fb(n),s=Nb(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=jb(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:jb(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}=Fb(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Bb(e){const t=nb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Wb(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:Bb(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 Hb extends Error{constructor(e,t,r){super(Wb({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 Wb({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function qb(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}}var zb=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Gb="2026-07-28",Vb=-32022,Kb="io.modelcontextprotocol/protocolVersion",Jb="io.modelcontextprotocol/clientCapabilities",Zb="io.modelcontextprotocol/clientInfo",Xb="io.modelcontextprotocol/serverInfo",Qb={name:"cursor",version:"1.0.0"},Yb=new Map;function eS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tS(e){const t=new URL(String(e));return t.hash="",t.href}function rS(e,t){const r=Yb.get(e);return!(void 0===r||r<=t()&&(Yb.delete(e),1))}function nS(e,t){try{return tS(e)===t}catch{return!1}}function oS(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}function sS(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Gb),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=eS(o.params)?o.params:{},a=eS(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===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,[Kb]:Gb,[Jb]:n.capabilities,[Zb]:n.clientInfo}}});return{...e,headers:s,body:l}}function iS(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function aS(e,t){const r=tS(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Qb}},s=!1;const i=()=>s||rS(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,sS(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!oS(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!eS(n)||!eS(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Gb))return iS({id:t,error:{code:Vb,message:"Unsupported protocol version",data:{requested:Gb,supported:s??[]}}});const i=eS(o._meta)?o._meta:{},a=eS(i[Xb])?i[Xb]:{name:new URL(r).hostname,version:"unknown"};return iS({id:t,result:{protocolVersion:zb.aE,capabilities:eS(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){Yb.set(e,t()+6e5)}(r,n)),d}return e(i,sS(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!nS(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!eS(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()&&nS(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=eS(l.message.params)?l.message.params:{};o={capabilities:eS(e.capabilities)?e.capabilities:{},clientInfo:eS(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?rS(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||!oS(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(!eS(r)||!eS(r.error))return!1;const n=r.error;if(n.code!==Vb||!eS(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Gb)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function cS(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()===Bv));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()!==Bv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function lS(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(Bv,i),r(n,{...o,headers:a,redirect:"manual"})}}class uS{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=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var dS=r("crypto");function hS(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function pS(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 fS(e,t){return pS(e,t)}function mS(e){if(e)return(0,dS.createHash)("sha256").update(e).digest("hex").slice(0,12)}function gS(e){if(e&&0!==e.length)return mS(JSON.stringify([...e].sort()))}function wS(e){return{clientIdHash:mS(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:gS(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function yS(e){return"object"==typeof e&&null!==e}function vS(e,t){let r=e;for(const e of t){if(!yS(r)||!(e in r))return;r=r[e]}return r}function bS(e,t){for(const r of t){const t=vS(e,r.split("."));if("string"==typeof t)return t}}function SS(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function kS(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 _S=e=>e;function CS(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?AS(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?AS(t(r)):void 0}}function ES(e){if(e&&"object"==typeof e)return yS(e)?e.cause:void 0}function xS(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const PS="[REDACTED]",IS=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function RS(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${PS}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${PS}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${PS}`)}function TS(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function AS(e,t){return TS(RS(e),t?.maxLength)}function $S(e,t=_S){if("string"==typeof e)return TS(RS(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")||IS.test(t)}(e)?PS:"string"==typeof r?RS(t(r)):r));if(!r)return;return TS(r)}catch{return}}function MS(e,t=_S){const r=ES(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=CS(r,t),i=CS(e,t)??s,a=bS(e,["code","cause.code"]),c=SS(e)??SS(r)??bS(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:AS(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=vS(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??kS(i)??kS(s),d=$S(vS(e,["response","body"])??vS(e,["body"])??vS(e,["data"])??vS(e,["cause","body"])??vS(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 hS({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:xS(e,t),sdkErrorKind:p})}const DS={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 OS(e){const t=e.message??DS[e.event],r={event:e.event,cursorMcp:{oauth:hS({...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 FS=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]))),NS=4096;function jS(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function LS(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function US(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function BS(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(US(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function WS(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function HS(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function qS(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:HS(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:HS(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:HS(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:HS(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:HS(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:HS(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:HS(t.get("content-length"))}}function zS(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 GS(e){const{input:t,init:r}=e,n=pS(LS(t)),o=function(e,t){const r=new Headers(BS(jS(e)?e.headers:void 0));return new Headers(BS(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=WS(o),i=o.get("content-type"),a=mS(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return FS.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(jS(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:qS(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function VS(e,t){const r=WS(e.headers),n=HS(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:mS(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:mS(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:KS(e.headers,"retry-after"),slackRateLimitType:KS(e.headers,"x-slack-ratelimit-type")}}function KS(e,t){return e.get(t)?.slice(0,64)??null}function JS(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 ZS(e,t){const r=GS({input:e,init:t});if(void 0!==zS(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 XS=e=>e;async function QS(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function YS(e){if(!ZS(e.input,e.init))return;const t=await QS(e.response,NS,e.redact);if(void 0!==t)try{return $S(JSON.parse(t))}catch{return AS(t,{maxLength:NS})}}async function ek(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 QS(t,NS,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=pS(LS(e.input)).path)&&!0!==t?.endsWith("/mcp"))return AS(e.rawText,{maxLength:NS});var t;try{const t=JSON.parse(e.rawText);return US(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!US(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?AS(r.message,{maxLength:NS}):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 YS({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function tk(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function rk(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=>rk(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,rk(n,t,r+1)])))}function nk(e,t){const r=e=>{const r=rk(e,t,0);return US(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 ok(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:nk(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await ek({input:s,init:i,response:e,redact:n??XS});return!r&&e.ok||tk((()=>{!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=GS({input:t,init:r}),l=zS(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:VS(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")&&!ZS(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:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!yS(e))return;const t=yS(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}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await ek({input:s,init:i,response:t,redact:n??XS}):{};throw tk((()=>{!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=MS(n,e.redactLogText),u=GS({input:t,init:r}),d=zS(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?VS(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:JS(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}Error,Error;const sk=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),ik=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),ak=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];function ck(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}}const lk=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],uk=[".exe",".cmd",".bat"],dk=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,hk=new Set(["py","pyw"]),pk=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),fk=new Set;function mk(e){return lk.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 gk(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of uk)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(dk.test(r)||hk.has(r)||"uvx"===r)return!0;if("uv"===r){const e=gk(t,pk);return"run"===e?.value||"tool"===e?.value&&"run"===gk(e.rest,pk)?.value}return"pipx"===r&&"run"===gk(t,fk)?.value}(n,o)?mk(i)||mk(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function yk(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 vk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),bk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Sk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),kk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),_k=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");function Ck(e){return`${typeof e}:${String(e)}`}function Ek(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(Ck(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Ck(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=Ck(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 xk(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,Js.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Pk{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,zb.vo)(e)&&(0,zb.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,zb.wU)(e)||await this.inner.send(e,t)}}const Ik=Nn.object({tools:Nn.array(Nn.unknown()),nextCursor:Nn.unknown().optional()}),Rk={typeFilled:0,toolDropped:0,outputStripped:0};function Tk(e){if(Fk(e))return"string"==typeof e.name?e.name:void 0}function Ak(e){return $k(e.issues.filter((e=>"outputSchema"===e.path[0])))}function $k(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function Mk(e){if(!Fk(e))return e;const t={...e};return delete t.outputSchema,t}function Dk(e){return Fk(e)&&!("type"in e)}function Ok(e,t){return{...e,inputSchema:{type:"object",...t}}}function Fk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Nk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const jk=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Nk.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,Js.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 Lk{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>=yb}append(e){const t=yb-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}=yi(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:vb(t),...r}))}catch{}}const Gk=(0,E.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 Vk(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Kk=["authorization_code","refresh_token"],Jk=["code"];class Zk{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=tb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(Hv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?rb:Yv}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled??(()=>!1),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,Js.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=()=>!1){const n=Xv(e);if(!0!==n?.pinsScopesOverConfiguredScopes){if(void 0!==t&&t.length>0)return t;const n=nb(e);return void 0!==n&&r(n.gate)?n.baseScopes:t}return void 0===n.scopesPinGate||r(n.scopesPinGate)?n.scopes??t:t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=Xv(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 Xk(e){const{serverName:t,config:n,tokenStorage:o}=e,{isScopeChallengeStepUpEnabled:s}=e,i=await _b(n.url,e.fetchImpl),a=pb({loopbackIpv4:i?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),c=function(e,t){const r=Sb(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:fb(t),grant_types:[...Kk],response_types:[...Jk],token_endpoint_auth_method:"none"}}(n.auth,a),l=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:c});return new Zk({identifier:t,redirectUrl:a,serverUrl:n.url,restMcpProviderMetadata:i,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:fb(a),token_endpoint_auth_method:"none",grant_types:[...Kk],response_types:[...Jk],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...void 0!==s&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Ub({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),isEnabled:async()=>s(),readScopesSupported:t=>async function(e){try{const{discoverOAuthProtectedResourceMetadata:t}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"));return(await t(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch)).scopes_supported}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:l,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:l?.client_id})})}const Qk=new Set;let Yk=!1;function e_(){for(const e of Qk)try{process.kill(e,"SIGKILL")}catch{}}function t_(e,t){return aS(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function r_(e,t,r){const n=cS(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?lS((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class n_{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 uS,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}})();OS({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(){return new bk.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}},extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}},jsonSchemaValidator:jk})}setupElicitationHandler(){this.client.setRequestHandler(zb.$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){const d=new URL(t.url);o=o??lb;const h=await Xk({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,isScopeChallengeStepUpEnabled:u}),p=h.tokens(),f=cS(t.url,n),m=f.headers,g=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),w=void 0!==f.cursorAuthHeaderValue&&void 0!==f.cursorAuthOrigin&&void 0!==g?lS((()=>f.cursorAuthHeaderValue),f.cursorAuthOrigin,g):g,y=e=>void 0===w||void 0===i?w:ok({fetch:w,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let v;const b=e=>{const r=h.scopeStepUp,n=e??g;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,vk.j2)(h,{serverUrl:d.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==w?{fetchFn:w}:{}});const r=h.lastRedirectUrl;v=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:qb(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){Eb(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 Hb(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},S=n_.createClient(),k=e=>e instanceof vk.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&sk.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!ik.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&&ak.some((e=>e.test(n)))}(e)}(e),_=async t=>{if(!h.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!==v&&v.redirectUrl===h.lastRedirectUrl?v.resourceMetadataUrl:void 0;await(0,vk.j2)(h,{serverUrl:d.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==w?{fetchFn:w}:{}}),a&&OS({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...fS(d.toString()),...ck(h.tokens(),{expiresInIsFresh:!0})}})},C=r=>{const n=h.lastRedirectUrl?.toString?.()??"",o=new n_(e,S,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await _(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:h,authCodeExchange:_,sessionId:r,config:t});return o},E=async()=>{const r=new Sk.A(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(y("sse"))});try{return await S.connect(r),new n_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await r.close().catch((()=>{})),k(t))return a&&OS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(p?.refresh_token),...fS(d.toString()),...MS(t,i?.redactLogText)}}),C();throw t}};if("sse"===t.type)return E();const x=new _k.j(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(t_(y("streamableHttp"),d))});try{await S.connect(x);const r=function(e,t=Date.now){return rS(tS(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:xk({url:t.url,headers:n,accessToken:h.tokens()?.access_token})}}(S,x);return new n_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,sessionId:x.sessionId,protocolVersion:x.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(k(t))return a&&OS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(p?.refresh_token),...fS(d.toString()),...MS(t,i?.redactLogText)}}),C(x.sessionId);if(function(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)}(t))return E();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=n_.createClient(),o=new _k.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new n_(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=lb,i,a,c,l,u){const d=new URL(t.url),h=await Xk({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=r_(t.url,o,i),m=new _k.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ok({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=n_.createClient();return await g.connect(m),new n_(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=lb,i,a,c,l){const u=await Xk({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(xk({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=r_(t.url,o,i),p=new _k.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=n_.createClient();return await f.connect(new Pk(p,r.result)),new n_(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 _k.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{Bk(s,(0,i.VI)(e.withName("McpSdkClient.fromCommand")),!1);const u=(l=o?.spawn,void 0!==l||"linux"!==process.platform?l:(e,t,r)=>(0,Sl.D9)(bl.spawn,e,t,r)),d=r.args??[],h=new kk.oQ({command:r.command,args:d,env:wk({command:r.command,args:d,env:n}),cwd:r.cwd,stderr:"pipe",...u&&{spawn:u}}),p=function(e){const t=new Lk;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>AS(t.text.replace(/\s+/g," ").trim(),{maxLength:yb}),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)}))}}}(h.stderr),f=n_.createClient(),m=o?.connectTimeoutMs??(void 0!==(c=r.startupTimeoutSec)&&Number.isFinite(c)&&c>0?Math.min(1e3*c,3e5):6e4);let g;h.onclose=()=>{var e;void 0!==g&&(e=g,Qk.delete(e))};const w=new AbortController,y=f.connect(h,{timeout:m,signal:w.signal});let v;g=h.pid??void 0,void 0!==g&&(a=g,Qk.add(a),Yk||(Yk=!0,process.on("exit",e_)));const b=new Promise(((e,r)=>{v=setTimeout((()=>r(new Error(`MCP server connection timed out after ${m}ms: ${t}`))),m)}));try{await Promise.race([y,b])}catch(e){throw w.abort(),y.catch((()=>{})),await h.close().catch((()=>{})),await p.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Uk.set(r,t),r}(e,p.read())}finally{void 0!==v&&clearTimeout(v)}return new n_(t,f,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==g,serverSignals:Ek(h)})}catch(e){s.error=e,s.hasError=!0}finally{Wk(s)}var a,c,l}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 _k.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 _k.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=Bk(t,(0,i.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Vk(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()=>{const e=await yk({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...Rk}}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}},Ik),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(Fk(e)){const r=e.inputSchema;Dk(r)&&(t=Ok(e,r),s++)}let n=zb.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=zb.Dn.safeParse(Mk(t));o.success&&(a++,r(Tk(e),Ak(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Tk(e),$k(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(s_.has(n))return s_.delete(n),s_.add(n),!1;if(s_.add(n),s_.size>256){const e=s_.keys().next().value;void 0!==e&&s_.delete(e)}return!0})(n,this.serverName,e??"")&&Hk.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+=t.typeFilled,i_(r.ctx,"type_filled",t.typeFilled),i_(r.ctx,"tool_dropped",t.toolDropped),i_(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:Ay(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:Ay(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){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,e,n),e instanceof vk.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const t=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(t,this.stateValue,"runtime_unauthorized",{...MS(e,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}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=zb.O4.MethodNotFound;if(t instanceof zb.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof vk.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof zb.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof _k.b||e instanceof Sk._){const t=e instanceof _k.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&&Hk.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 c=Bk(s,(0,i.VI)(e.withName("McpSdkClient.callTool")),!1);c.span.setAttribute("toolName",t),c.span.setAttribute("serverName",this.serverName),c.span.setAttribute("mcp.transport",Vk(this.config));const l=this._callToolLock,u=this._callToolQueueDepth;let d;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{d=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=Bk(e,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",u);const r=performance.now();await l;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),c.span.setAttribute("mcp.call_tool.lock_wait_ms",n),c.span.setAttribute("mcp.call_tool.queued_ahead",u)}catch(t){e.error=t,e.hasError=!0}finally{Wk(e)}}if("requires_authentication"===this.stateValue.kind)throw new vk.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const d=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=Bk(n,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const l=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===l.isError),zk(e,this.config,{isError:!0===l.isError}),{content:l.content,isError:!0===l.isError,structuredContent:(a=l.structuredContent,$y(a)),_meta:Uy(l._meta)}}catch(e){n.error=e,n.hasError=!0}finally{Wk(n)}}catch(t){t instanceof Hb?(zk(e,this.config,{error:t,httpStatus:t.decision.status}),function(e,t){try{Gk.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,t)):zk(e,this.config,{error:t});const r=t instanceof Hb&&"offer"===t.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==d;if((t instanceof vk.D_||r)&&"ready"===this.stateValue.kind){const e=this.stateValue,n=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:n,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,r?"scope_step_up":"runtime_unauthorized",{...MS(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,l.then(d)}}catch(e){s.error=e,s.hasError=!0}finally{Wk(s)}var a}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},zb.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(Bk(t,(0,i.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{Wk(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(Bk(t,(0,i.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 yk({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{Wk(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return Bk(r,(0,i.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{Wk(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return Bk(t,(0,i.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await yk({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{Wk(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return Bk(n,(0,i.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{Wk(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 o_=(0,E.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),s_=new Set;function i_(e,t,r){if(0!==r)try{o_.increment(e,r,{outcome:t})}catch{}}class a_ 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 c_{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new Xt(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class l_{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new c_({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class u_{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=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{Wk(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 d_{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=Bk(t,(0,i.VI)(e.withName("McpManager.getToolSet")),!1),n=Bk(t,h_(this.listingDeadlineAt),!1),o=await(0,or.PH)(Object.entries(this.clients),(([e,t])=>n.within(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(),a=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=a.get(t);void 0===r?a.set(t,[e]):r.push(e)}const c={};for(const[e,t]of a){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}`)),c[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},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 c_(c)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("McpManager.getInstructions")),!1),n=Bk(t,h_(this.listingDeadlineAt),!1),o=await(0,or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t.getInstructions(r.ctx)).then((e=>e&&0!==e.trim().length?new ds.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{Wk(t)}}}function h_(e){if(void 0===e)return{concurrency:4,within:e=>e,[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:e=>Promise.race([e,r]),[Symbol.dispose]:()=>clearTimeout(t)}}function p_(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 f_{constructor(e){this.options=e,OS({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:fS(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return OS({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...ck(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),OS({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...ck(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){OS({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){OS({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...MS(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return OS({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...wS(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),OS({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...wS(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(OS({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 m_{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 g_{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 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},y_=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_=(0,C.h)("DefinitionMcpLoader");function b_(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 S_(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function k_(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function __(e){return e?.length??0}function C_(e){if(void 0!==e)return(0,Js.createHash)("sha256").update(uv(e)).digest("hex")}function E_(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?$v(r):r)}async function x_(e,t,n,o,s={middlewares:[],configPath:""},a,c,l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=w_(u,(0,i.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);let f=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=w_(s,(0,i.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(k_);return await async function(e,t,n,o){const s=n.cwd?b_({filePath:n.cwd}):void 0;let i,a;if(n.args&&n.args.length>0)i=b_({filePath:n.command,baseDir:s}),a=n.args.map((e=>b_({filePath:e,baseDir:s})));else{const e=(0,Mv.A)(n.command);i=b_({filePath:e[0],baseDir:s}),a=e.slice(1).map((e=>b_({filePath:e,baseDir:s})))}const c=n.env??{},{startupTimeoutSec:l}=n,u=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),d=(0,hy.$H)(u);if(void 0!==d){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:h}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),p=s??process.cwd(),f=await n(d,p);v_.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=${__(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${__(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${__(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${C_(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:__(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:__(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:__(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:C_(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}));try{return await n_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c,{spawn:(e,t,r)=>h(e,t,r,f)})}catch(e){if(e instanceof o)throw new dv(t,e);throw e}}return!0===u?.enabled&&"no_sandbox"===u.mcpNetworkMode&&(!0===u.win32UserExtensionUnsandbox?v_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):v_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),n_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c)}(h,t,n,e)}if("url"in n){u.span.setAttribute("kind","url");const e=a?.(t);return await async function(e,t,r,n,o,s,i,a){const c=p_(e,v_),l=function(e,t,r){return{logger:{debug:(t,r)=>v_.debug(e,t,r),info:(t,r)=>v_.info(e,t,r),warn:(t,r)=>v_.warn(e,t,r),error:(t,r,n)=>v_.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:E_(r)}}(e,t,a),u=void 0!==s&&mv(r.url)?gv(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return n_.fromStreamableHttp(t,r,n,r.headers,o,u,l,c,void 0,void 0,i)}(h,t,n,o,e,d.find(S_),c,l.isLinkSharedPaymentTokenLogRedactionEnabled)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{y_(s)}};for(const e of d){const r=f;f=async(n,o)=>await e.load(n,t,o,h,r)}try{return await f(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=Uk.get(e);void 0!==r&&Uk.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=wv(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 I_{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{w_(r,(0,i.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=E_(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Uk.get(e)}(r);v_.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 d_(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{y_(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(k_);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,uv(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(v_.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{w_(n,(0,i.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 a;try{a=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,a),a}catch(e){n.error=e,n.hasError=!0}finally{y_(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new m_(this.tokenStorage,n),s=p_(e,v_),i=new f_({inner:o,logger:s,redactLogText:E_(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new g_(i):i;return x_(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.isScopeChallengeStepUpEnabled,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){v_.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 wy||e instanceof yy||e instanceof vy||e instanceof R_}(r)}}class R_ 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 T_=[1e3,3e3];class A_{constructor(e){this.blockingService=e}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={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked)throw new R_(t,i.reason??"teamPolicy",i.message);for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),t}catch(e){if(e instanceof pv)throw new R_(t,"teamPolicy",e.message);const r=e instanceof fv?T_[n]:void 0;if(void 0===r)throw e;await(0,or.cb)(r)}}}class $_ extends I_{constructor(e,t,r=[],n={}){super(new P_(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new $_(t,e,r)}}function M_(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 D_=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function O_(e){const t=D_.VE.safeParse(e);return t.success?t.data:void 0}function F_(e){const t=D_.H5.safeParse(e);return t.success?t.data:void 0}class N_{constructor(e){this.mcpAuthPath=e;const t=N_.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,N_.mcpAuthPromises.set(e,t),t.catch((()=>{N_.mcpAuthPromises.get(e)===t&&N_.mcpAuthPromises.delete(e)}))}N_.saveLocks.has(e)||N_.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,Ys.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=O_(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?O_(n.tokens):void 0,clientInfo:"clientInfo"in n?F_(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=N_.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;N_.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,Ys.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,Ys.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}N_.mcpAuthPromises=new Map,N_.saveLocks=new Map;const j_=Buffer.from([137,80,78,71,13,10,26,10]),L_=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),U_=e=>{if(e.lengthe.subarray(e.length-L_.length).equals(L_)||(e=>{let t=j_.length+25;for(;t+L_.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-L_.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+L_.length).equals(L_);t+=L_.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)}},B_=e=>1===e||e>=208&&e<=216,W_=e=>192===e||193===e||194===e,H_=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,q_=e=>0===e||e>=208&&e<=215,z_=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=U_(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(B_(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=z_(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(B_(r)){t+=2;continue}if(218===r||217===r||H_(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(W_(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),V_=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),K_=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,j_.length).equals(j_)?"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},Z_={0:1,2:3,4:2,6:4},X_=({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}`)}}},Q_=({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)},eC={0:1,2:3,3:1,4:2,6:4},tC=[1,2,4,8,16],rC=[[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]],nC=async e=>{const t=oC(e);if(void 0===t)return;const r=sC(t);let n=0;const o=nh.Readable.from(t.idat).pipe((0,sh.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`)},oC=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=eC[i[9]];if(void 0===e||!tC.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}},sC=({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?rC.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const iC=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},aC=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),cC=e=>{if(!aC(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)}}},lC=e=>iC().decode(e),uC=e=>iC().encode(e);async function dC(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);G_(e.data);return e.resizeWithoutBudget(e.data)}const hC=[{width:1280,height:800},{width:1456,height:840}],pC=1048576,fC=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function mC(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 gC=(e,t,r=1024)=>mC(e,t,r),wC=(e,t,r)=>{e.resize({w:t,h:r})},yC=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`)},vC=(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:yC(((e,t)=>{switch(t){case"png":return(e=>{let t,r=j_.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=V_(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))}};const bC=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return dC({data:e,budgetBytes:r,maxImageBytes:pC,fitImage:mC,resizeWithoutBudget:e=>bC(e,n)})}if(aC(e))return(async(e,t)=>{const r=cC(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:fC(e),mimeType:"image/webp"};const n=void 0!==r&&hC.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!gC(r.width,r.height,1280).needsResize)&&e.length<=pC)return{data:fC(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:fC(e),mimeType:"image/webp"};yC(r);const o=await lC(e),s=(await cw()).fromBitmap({data:Buffer.from(o.data),width:o.width,height:o.height});let{width:i,height:a,needsResize:c}=n?{width:s.bitmap.width,height:s.bitmap.height,needsResize:!1}:gC(s.bitmap.width,s.bitmap.height,1280);c&&wC(s,i,a);let l=await uC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});for(;l.length>pC&&i>8&&a>8;)i=Math.max(8,Math.round(.8*i)),a=Math.max(8,Math.round(.8*a)),wC(s,i,a),l=await uC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});return{data:fC(l),mimeType:"image/webp",reencoded:!0}})(e,t);const r=G_(e);if(void 0!==r&&e.length<=pC&&!gC(r.width,r.height).needsResize)return{data:fC(e),mimeType:r.mimeType};const n=J_(e);void 0!==n&&vC(e,n),"png"===n&&await nC(e);const o=await cw(),s=void 0===r?void 0:gC(r.width,r.height),i="image/png"===r?.mimeType&&!0===s?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(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=Z_[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}})(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{})):void 0,a=void 0===i?await o.read(e):o.fromBitmap(i),c=(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"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=gC(a.width,a.height);if(void 0===i&&!h&&e.length<=pC&&l===c)return{data:fC(e),mimeType:c};let p=u,f=d;h&&wC(a,p,f);let m=await a.getBuffer(l);for(;m.length>pC&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),wC(a,p,f),m=await a.getBuffer(l);return{data:fC(m),mimeType:l,reencoded:!0}},SC=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=J_(t);let n;if(aC(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{vC(t,r);const e=await cw();n=async()=>("png"===r&&await nC(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}};function kC(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 _C(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=fi(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?.[Dv]}(e)&&(t[Dv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}var CC=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},EC=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 xC=(0,E.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),PC=(0,E.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),IC=(0,E.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),RC=(0,E.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),TC=(0,E.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"]}),AC=(0,E.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"]}),$C=(0,C.h)("McpFileSystemWriter"),MC="mcpFsStructuredLogOptIn";function DC(e,t){return t?.includeStructuredLogs?{...e??{},[MC]:!0}:e}const OC={debug(e,t,r,n){$C.debug(e,t,DC(r,n))},info(e,t,r,n){$C.info(e,t,DC(r,n))},warn(e,t,r,n){$C.warn(e,t,DC(r,n))},error(e,t,r,n,o){$C.error(e,t,r,DC(n,o))}},FC="mcps",NC="tools",jC="~staging",LC="~prev",UC="mcp_auth",BC="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.",WC="# >>> CURSOR MANAGED BLOCK >>>",HC="# <<< CURSOR MANAGED BLOCK <<<",qC=["# 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 zC(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function GC(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function VC(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function KC(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 JC(e){if(Array.isArray(e))return e.map((e=>JC(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,JC(t)]));return Object.fromEntries(t)}return e}function ZC(e){return JSON.stringify(JC(e))}function XC(e){const t=e.map((e=>({value:e,key:ZC(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function QC(e){const t=XC(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=XC(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=XC(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return ZC({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 YC{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=>{OC.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),OC.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=`${WC}\n${qC}\n${HC}\n`;let n;await(0,Ys.mkdir)(e,{recursive:!0});try{n=await(0,Ys.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==el(e))throw e}if(void 0===n)return void await(0,Ys.writeFile)(t,r);const o=n.indexOf(WC),i=n.indexOf(HC,o+30);if(-1===o||-1===i)await(0,Ys.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Ys.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{OC.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,FC);try{const e=await(0,Ys.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(jC))).map((e=>(0,Ys.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==el(e)&&OC.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:qt(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:qt(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){OC.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,ye.q6)();return e&&(t=t.with(C._O,e)),t}getLogContext(e){return e.with(C._O,this.ctx.get(C._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return VC(this.mcpAuthCopyOverrides?.authToolDescription)??BC}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Lt(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return VC(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=VC(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:UC},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Lt(e)?this.getNeedsAuthStatusMessage(e):VC(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){OC.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${tl(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(OC.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 zC(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||OC.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?zC(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?zC(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?zC(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:KC(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=cE(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,FC,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=cE(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,FC,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===UC))||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:UC,name:UC,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)?OC.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):OC.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===UC))){const t=e.tools.find((e=>e.toolName===UC));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??[])];OC.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=>(OC.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 OC.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${tl(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=>{OC.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):OC.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)),OC.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=cE(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{CC(r,(0,i.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!qt(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=>(OC.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(OC.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);OC.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){OC.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{EC(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,NC,`${GC(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{CC(n,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),a=(0,s.join)(this.projectDir,FC);await(0,Ys.mkdir)(a,{recursive:!0});const c=new Map;for(const e of t)try{c.set(e.serverIdentifier,QC(e))}catch(t){OC.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),c.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==c.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&OC.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,Ys.stat)((0,s.join)(a,e.sanitizedId))}catch{OC.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!c.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??cE(e);r.has(n)?(OC.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),c.set(e,this.cachedFingerprints.get(e))):(OC.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}const d=void 0===this.cachedServerData;if(d)try{const e=await(0,Ys.readdir)(a),t=new Set(e.filter((e=>!e.endsWith(jC)&&!e.endsWith(LC))));for(const r of e)if(r.endsWith(jC))await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else if(r.endsWith(LC)){const e=r.slice(0,-5);if(t.has(e))await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else try{await(0,Ys.rename)((0,s.join)(a,r),(0,s.join)(a,e)),t.add(e)}catch{await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);c.has(t)||c.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){OC.error(o,"Error clearing mcps directory",e)}const h=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));OC.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:h,unchangedServerCount:t.length-l.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:d,projectDirHash:(0,Js.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const p=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,a))));for(let t=0;t(0,Ys.rm)((0,s.join)(a,e),{recursive:!0,force:!0}))));for(let r=0;r{}))}catch(e){n.error=e,n.hasError=!0}finally{EC(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{CC(n,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,Ys.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,NC);await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=GC(r.toolName),n=(0,s.join)(e,`${t}.json`),o=Wt(r);await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=GC(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=GC(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,Ys.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,Ys.writeFile)(e,r)}const a=(0,s.join)(o,"SERVER_METADATA.json"),c={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,Ys.writeFile)(a,JSON.stringify(c,null,2))}catch(e){n.error=e,n.hasError=!0}finally{EC(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;CC(r,(0,i.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&&OC.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const a=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=GC(t.toolName),n=(0,s.join)(e.folderPath,NC,`${r}.json`);return new ds.E$({toolName:t.toolName,definitionPath:n,..._C(t.annotations)})}));return new ds.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,a,"workbench_lease"),new ds.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){r.error=e,r.hasError=!0}finally{EC(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&&OC.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){OC.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&OC.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){OC.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{CC(t,(0,i.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),a=(0,s.join)(this.projectDir,FC),c=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=cE(e.serverIdentifier),r=(0,s.join)(a,t),n=e.tools.map((e=>{const t=GC(e.name);return new ds.E$({toolName:e.name,definitionPath:(0,s.join)(r,NC,`${t}.json`),..._C(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===UC))){const e=GC(UC);n.push(new ds.E$({toolName:UC,definitionPath:(0,s.join)(r,NC,`${e}.json`)}))}return new ds.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})})),l=c.reduce(((e,t)=>e+t.tools.length),0);return OC.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${c.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,c,"snapshot"),new ds.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:c})}catch(e){t.error=e,t.hasError=!0}finally{EC(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{OC.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,FC),i=new Set,a=new Map;for(const e of t){const t=cE(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Ys.readdir)(o),c=c.filter((e=>!e.endsWith(jC)&&!e.endsWith(LC)))}catch(e){if("ENOENT"!==el(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++,xC.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),OC.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++,xC.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,NC);let h=0;try{h=(await(0,Ys.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,xC.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),OC.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}))}PC.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),IC.gauge(e,i.size,this.getMetricTags({mcp_source:r})),RC.gauge(e,l.size,this.getMetricTags({mcp_source:r})),TC.gauge(e,d,this.getMetricTags({mcp_source:r})),AC.gauge(e,p,this.getMetricTags({mcp_source:r})),OC.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||OC.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())}}YC.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var eE=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},tE=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 rE(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 nE=(0,C.h)("local-exec:mcp");function oE(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function sE(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function iE(e){return new er._Z({content:{case:"image",value:new er.do({data:e.data,mimeType:e.mimeType})}})}function aE(e){return new er._Z({content:{case:"text",value:new er.zN({text:e})}})}function cE(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 lE(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client}});if(!n)return;const o=await hu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new er.iz({result:{case:"error",value:new er.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:$w.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 er.iz({result:{case:"approved",value:new er.Ke}}):null:new er.iz({result:{case:"rejected",value:new er.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new er.iz({result:{case:"error",value:new er.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class uE{constructor(e,t,r,n,o=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}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}}(zt(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=eE(r,(0,i.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,a=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[a]));const c=await this.toolSet.getTools(o),l=Array.from(new Set(c.map((e=>e.clientKey)))).sort(),u=c.find((e=>e.clientKey===a&&e.toolName===t.toolName)),d=c.find((e=>e.name===t.name));if(void 0!==d&&(void 0!==u?d!==u:d.toolName!==t.toolName||d.clientKey!==a&&d.providerIdentifier!==a))return new er.iz({result:{case:"error",value:new er.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${a}" that the call names.`})}});const h=void 0===u?void 0:await this.toolSet.getClient(o,u.clientKey).catch((()=>{})),p=await lE(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u,...void 0===h?{}:{client:h}});if(void 0!==p)return p;const f=await this.toolSet.getToolSet(o);let m;try{m=await f.execute(u?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(Qt(r)&&t.providerIdentifier.length>0&&!c.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new a_(t.providerIdentifier,l)),r instanceof a_){const e=await this.describeDisconnectedServer(o,[a,t.providerIdentifier]);return void 0!==e?new er.iz({result:{case:"error",value:new er.Nh({error:e})}}):new er.iz({result:{case:"serverNotFound",value:new er.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Qt(r))return new er.iz({result:{case:"toolNotFound",value:new er.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const g=[];for(const e of m.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)g.push(aE(e.text));else if("resource"===r){const r=jy(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await bC(n).then(iE,(e=>{nE.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));g.push(s??aE(Ly(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 bC(s)}catch(e){nE.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)}),g.push(aE(`[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}g.push(iE(i))}else if("image"!==r){const t=Ly(e);g.push(aE(t))}}const w=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 er._Z({content:{case:"text",value:new er.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:g,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.default.join(t,pl),n=s.default.join(r,`${(0,Js.randomUUID)()}.txt`);await(0,Ys.mkdir)(s.default.dirname(n),{recursive:!0});const o=fi(e,fl),i=ma(o),a=Buffer.byteLength(o,"utf8");return await(0,Ys.writeFile)(n,o,"utf8"),new yl.pV({filePath:n,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===w)throw new Error("Failed to materialize MCP text output");const y=m.structuredContent&&"object"==typeof m.structuredContent&&!Array.isArray(m.structuredContent)?sr.Struct.fromJson(m.structuredContent):void 0,v=new er.QW({content:w,isError:m.isError,structuredContent:y,resultMeta:void 0===m._meta?void 0:sr.Struct.fromJson(m._meta)});return new er.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{tE(r)}var n}}class dE{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=eE(r,(0,i.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 er.kP({result:{case:"error",value:new er.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new er.kP({result:{case:"success",value:new er.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 er.kP({result:{case:"success",value:new er.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new er.kP({result:{case:"error",value:new er.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{tE(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 er.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:rE(e.annotations)}))):[]}}class hE{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Mt),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=eE(r,(0,i.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:$w.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:sr.Value.fromJson(t.server),uri:sr.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:sr.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new er.ZD({result:{case:"rejected",value:new er.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const a=await this.mcpLease.getClients(n),c=a[t.server]??Object.values(a).find((e=>e.serverName===t.server));if(!c)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await c.getState(n)).kind)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await c.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new er.ZD({result:{case:"notFound",value:new er.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,Ys.realpath)(r),o=s.default.resolve(r,t.replace(/^\/+/,""));if(!oE(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.default.dirname(o);for(;;)try{if(!oE(n,await(0,Ys.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==sE(e))throw e;const t=s.default.dirname(i);if(t===i)throw e;i=t}if(await(0,Ys.mkdir)(s.default.dirname(o),{recursive:!0}),!oE(n,await(0,Ys.realpath)(s.default.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,Ys.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==sE(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,Ys.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,Ys.writeFile)(e,t)}return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:rE(r.annotations),metaJson:Bt(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:rE(r.annotations),metaJson:Bt(r._meta),content:{case:"blob",value:e}})}})}return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return nE.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{tE(r)}}}async function pE(e,t){const r=cE(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Ys.readdir)(n)}catch(e){if("ENOENT"===el(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,Ys.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 fE=(0,C.h)("local-exec:mcp-disk-freshness-on-access"),mE="/mcps/",gE=(0,E.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),wE=(0,E.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),yE=(0,E.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),vE=(0,E.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),bE=new Map;function SE(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function kE({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 fE.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>cE(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void fE.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"};gE.increment(e,1,{...l,outcome:c}),wE.histogram(e,i.length,l),yE.histogram(e,a.length,l),vE.histogram(e,i.length+a.length,l),"mismatch"===c&&fE.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 _E(e,t,r,n=pE){if(void 0===r||(void 0===(o=r)||!SE(o).includes(mE)))return;var o;const s=function(e){const t=SE(e),r=t.indexOf(mE);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=bE.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{bE.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=cE(r.serverIdentifier);await kE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await kE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{fE.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);bE.set(i,d)}async function CE(e){try{return(await(0,Ys.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function EE(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 xE(e,t,r=CE){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:EE(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}const PE=BigInt(0),IE=BigInt(8),RE=BigInt(16),TE=BigInt(65535);function AE(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function $E(e){const t=e.split(".");if(4!==t.length)return;let r=PE;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<>RE&TE)),t.push(Number(o.value&TE))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function DE(e){return $E(e)??function(e){const t=AE(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=ME(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 FE(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=>OE(e,t)))}(r.hostname,t)}function NE(e){return e.trim().toLowerCase()}function jE(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function LE({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":NE(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(NE).filter((e=>e.length>0)),n=void 0===e?void 0:NE(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:jE(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}const UE=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function BE(e){return e.trim().split(/\s+/).filter(Boolean)}function WE(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 BE(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return UE.has(n)}function HE(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=HE(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(zE(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(zE(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(zE(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const VE=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],KE=["cursor","molten glass"];function JE(e){return VE.some((t=>e===t||e.startsWith(`${t}.`)))}const ZE=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],XE=[{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"},...ZE,{bundleId:VE[0],name:"Cursor"}];function QE(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=XE.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}:JE(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>KE.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:VE[0],name:"Cursor"}:void 0}const YE=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 ex(e){return YE.has(e.toLowerCase())}function tx(e){return`app/${e}`}function rx(e){return"object"==typeof e&&null!==e}function nx(e){return sx.includes(e)}function ox(e){if(!rx(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!rx(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!nx(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 sx=["pid","bundleId","path","appName"],ix=/^[+-]?\d+$/;var ax=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const cx="win32"===process.platform;function lx(e,t){return cx&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const ux=(0,s.join)((0,o.homedir)(),".cursor","projects"),dx=(0,s.join)((0,o.homedir)(),".cursor","worktrees");function hx(e){return lx(ux,e)&&e!==ux}function px(e){return lx(dx,e)&&e!==dx}function fx(e,t){const r=function(e){if(!lx(ux,e))return;if(e===ux)return;const t=(0,s.relative)(ux,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function mx(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function gx(e){const t=el(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:tl(e)}}}async function wx(e,t){const r=(0,bi.o1)(e,t);try{return mx(await(0,Ys.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==el(e))return mx(r,r,gx(e));try{if((await(0,Ys.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Ys.readlink)(r)}catch{}return mx(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return mx(await(0,Ys.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==el(e))return mx(r,r,gx(e))}return mx(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===el(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,Ys.realpath)(t);return mx((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==el(t))return mx(e,e,gx(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return mx(e,e,{status:"newFile"})}(r):mx(r,r,gx(e))}}}function yx(e){return"resolved"===e.status||"newFile"===e.status}function vx(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 bx({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o}){return"workspace"===r.boundary&&!Sx(t,n)&&!Sx(t,o)&&!(_x(t,r.allowPaths)||e!==t&&_x(e,r.allowPaths))}function Sx(e,t){return t.some((t=>(0,bi.BJ)(e,t)))}function kx(e){return e.flatMap((e=>{const t=(0,bi.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function _x(e,t){const r="win32"===process.platform?bi.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,bi.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&Yi(r(t),n)}))}const Cx=/(?{const t=await wx(e);return yx(t.resolution)?t.resolvedPath:(0,bi.o1)(e)})))}function Nx(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 jx(e){return[...new Set(e)]}function Lx(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Ux({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 Bx(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Wx(e){return"<"!==e.operator&&"<&"!==e.operator}function Hx(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function qx(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function zx({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(yx(a.resolution)){for(const e of r){const t=await o(e);if(yx(t.resolution)&&Ux({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:s}))return"workspace-file"}return n&&tP(a.resolvedPath,i)?"tmp-file":void 0}}function Gx(e){return jx(e.map((e=>e.trim())).filter(Boolean))}function Vx(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 Kx(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Jx(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new xr.r6({type:"word",value:e})));return new xr.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Zx(e,t={}){return{type:e,...t}}function Xx(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 Qx(e,t){if("workspace"===e&&void 0!==t)return t}const Yx={workspace:0,system:1};function eP(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 tP(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){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||!Ux({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 rP(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,ri.$b)(e.networkPolicy),n=(0,ri.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,ri._B)(e.networkPolicy),s=(0,ri._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!(Yx[i]>Yx[a])}class nP{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&rP(t,r);this.state=o?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!rP(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function oP(e){return e?.type??"undefined"}const sP=["skills","skills-cursor","rules","plugins"];async function iP(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function aP(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function cP({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 lP=/^\s*Read\s*\((.*)\)\s*$/,uP=/^\s*Write\s*\((.*)\)\s*$/;class dP{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.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy}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]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]):[[],[]],i=r.map((e=>this.compileReadDenyMatcher(e))),a=e=>i.some((t=>t(e)));return async(e,r)=>a(e)||a(r)||n&&bx({requestedAbsolutePath:e,realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s})}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:Xx(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 Fx([...kx(e),...(0,ri.r5)()])}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,Zs.r_)(e)))),...sP.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,ri.W1)(e)??[]));return Fx([...this.rootDirectories,...r,...n])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,bi.o1)(e),o=await al(n);if(null===o)return{type:"unsafeResolution",message:Nx("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(!hx(o)&&!px(o)&&!t&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:o,requestedAbsolutePath:n});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const{perms:r,setting:n}=await this.readControlSetting();if("workspace"!==n.boundary||"unrestricted"===r.approvalMode)return!1;const o=await this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName);return!Sx(e,o)&&(!!bx({requestedAbsolutePath:t,realAbsolutePath:e,setting:n,resolvedWorkspaceRoots:o,resolvedAllowFolders:await this.resolvedReadAllowFolders(n.allowPaths)})&&{type:"needsApproval",approvalReason:n.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 shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Px(n,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const a=await wx(t);if(!yx(a.resolution))return{type:"unsafeResolution",message:vx(a.originalPath,a.resolution)};const c=a.resolvedPath,l=c;if(await this.ignoreService.isRepoBlocked(l))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",c))return{type:"permissionsConfig"};const u=a.originalPath.split(s.sep).pop()?.toLowerCase()??"",d=c.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===u||".cursorignore"===d)return{type:"permissionsConfig"};const h=hx(l),p=px(l),f=!h&&!p&&await this.ignoreService.isCursorIgnored(l);if(h||p);else if(f)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",c))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(c))return!1;const m=await this.getPermissions();if("workspace_readonly"===m.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===m.approvalMode)return!1;for(const e of this.rootDirectories){const t=await wx(e);if(!yx(t.resolution))continue;const r=t.resolvedPath;if((0,bi.BJ)(c,r)){const e=(0,s.relative)(r,c).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const g=async()=>{let e,t,n="";try{n=await sc(c),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,ax.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 w,y=!1;for(const e of this.rootDirectories){const t=await wx(e);if(!yx(t.resolution))continue;const r=t.resolvedPath;if((0,bi.BJ)(c,r)){y=!0,w=r;break}}const v=y?void 0:function(e){if(!px(e))return;const t=(0,s.relative)(dx,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(dx,t[0]):void 0}(c);if(!y&&void 0===v){if(function(e){return tP(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(c))return!1;if(fx(c,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(c.startsWith(e)){const e=c.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const b=w??v,S=c;let k=(0,s.relative)(b,S).split(s.sep);if(k=k.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&k.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${k[k.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,ri.OK)(c,b)){const e=k[k.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const _=await this.checkCursorFileProtection(k);if(_)return _;if(!0===m.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await g();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{Ix(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 al(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Nx("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}}:{kind:"allow"}}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(Rx.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:oP(l),requestedPolicyType:oP(n),effectiveRequestedPolicyType:oP(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Wr(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 Rx.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:oP(l),requestedPolicyType:oP(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.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,v="allowlist"===a&&i.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==v,S=v?v.map(Jx):d,k=void 0!==v?v.map(Vx):S.map((e=>[e.fullText.trim()].filter(Boolean))),_=void 0!==y?y.commands.map(Vx):k;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,ri.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,ri._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 C;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,ri.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,ri.wG)(Qx(e.readBoundary,e.additionalReadPaths),Qx(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),m&&Rx.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});const E=[],x=[];let P=[],I=[],R=[];const T=Gx(i.smartAllowlistDenylist??[]);if(T.length>0){I=[];const t=_.map((e=>e[0]??""));for(let e=0;e<_.length;e++){const r=_[e];if(r&&0!==r.length&&T.some((e=>Kx(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(Rx.info(e,"Command blocklist: commands require approval",{count:I.length}),E.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));Rx.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const n=k.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(WE(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),Gx(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=GE(P,R),t=e.length>0?e.join(", "):P.join(", ");x.push(`Not in allowlist: ${t}`)}C=o&&0===I.length,C&&Rx.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,$=S.map(((e,t)=>new nP(e,n,A,k[t])));if((0===S.length||f&&!b)&&!c){Rx.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:oP(n),userConfiguredPolicyType:oP(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const o={type:$w.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:w}};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{allRedirectsAreWorkspaceFileSafe: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 j=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:I});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return Rx.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=Wr(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&&Cx.test(r)||xx(r,Cx,Ex)||xx(r,/(?0&&(j.hasSecurityDenies||j.hasSoftDenies||!j.allCommandsRunnable);if(void 0!==g&&G.push(g),L&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),E.length>0&&(V||G.push(...E),z=!1),!V)if(b&&x.length>0)G.push(...x);else if(j.unapprovedCommands.length>0){const e=GE(this.generateAllowlistPatterns(j.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):j.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(j.hasSecurityDenies&&(V||(j.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),j.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${j.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=j.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");Rx.info(e,"Shell permissions: commands not in team allowlist",{commandCount:j.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J=G.join(" • "),Z=[];if(z){const e=void 0!==g?$.filter((e=>"allowlisted"!==e.state)):j.unapprovedCommands;Z.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const X=b&&x.length>0,Q=X?P:Z,Y=X&&R.length>0?R:void 0,ee="insecure_none"!==n.type&&"insecure_none"!==l.type,te="insecure_none"!==n.type,re=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,E.length>0?"command_blocklist":void 0,b&&x.length>0?"smart_allowlist_miss":void 0,j.unapprovedCommands.length>0?"unapproved_commands":void 0,j.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Rx.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:oP(n),userConfiguredPolicyType:oP(l),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:z,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:re,commandCount:$.length,unapprovedCommandCount:j.unapprovedCommands.length,deniedCommandCount:j.deniedCommands.length,notInTeamAllowlistCount:j.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSecurityDenies:j.hasSecurityDenies,hasSoftDenies:j.hasSoftDenies});const ne={type:$w.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&ee,isSandboxEnabled:"allowlist"===a&&te,canAllowlist:z,notAllowedCommands:Q,suggestedAllowlistEntries:Y,smartModeApprovalReason:g,smartModeApprovalRequestId:w}};r.onApprovalRequested?.();const oe=await this.pendingDecisionStore.requestApproval(ne);if(oe.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.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,d=l?c.commands.map(Jx):u;if(0===d.length)return!1;const h=l?c.commands.map(Vx):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Vx):h,f={type:"insecure_none"},m=d.map(((e,t)=>new nP(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=Gx(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>Kx(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const w=await this.teamSettingsService.getAutoRunControls();if(void 0!==w&&m.some((e=>this.isInTeamBlocklist(w,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:w,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const{userSandboxDataFolderName:t,teamAdminPolicy:r}=await this.getPermissions(),n=void 0!==t&&t.length>0?(0,s.join)((0,o.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,i=await this.foldPerUserFilePolicy(e,n),a=i.skipStatsigDefaults?i:await this.applyStatsigDefaults(i),c=await this.loadPerRepoFilePolicy(a.type);if("unavailable"===r){const{policy:e}=await(0,ri.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,ri.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const l=void 0===r?await this.buildTeamAdminPolicy(a.type):Zx(a.type,function(e){return"workspace"===e.readBoundary?e:void 0===e.networkPolicy?{}:{networkPolicy:e.networkPolicy}}(r)),u=(0,ri._B)(e.networkPolicy),{policy:d}=await(0,ri.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c,teamAdmin:l});return u?{...d,networkPolicy:(0,ri.T6)()}:d}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,ri.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,ri.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,ri.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};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,ri.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,ri._B)(e.networkPolicy))return e;const r={default:"deny",allow:jx(t.allowlist)};return{...e,networkPolicy:(0,ri.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,ri.tv)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Zx(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await 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:jx(i.allowlist)}:{},...i.denylist.length>0?{deny:jx(i.denylist)}:{}}:void 0:(0,ri.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});return void 0===t?void 0:Zx(e,t)}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){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return 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=wx,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=Lx();for(const e of l){if(qx(e))continue;const o=u?Lx():d,{operator:s,targetText:l}=e,p=e.destinationFds;if(">&"===s){const e=Hx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===s){const e=Hx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!Bx(s)||void 0===l){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await zx({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(Wx))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c,redirectsAllowlistSafe:l}}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?{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=this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:$w.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",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}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=oa({matchForms:t.parsingResult?ea({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(Rx.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.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==eP(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=eP(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){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return 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 n of e)WE(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?lP:uP}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=Qi(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,bi.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,bi.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 Yi(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{Px(o,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:a,providerIdentifier:c,args:l}=t,u=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:kC(r.annotationsJson)}(t,r?.annotations),d=e=>{this.mcpAllowlistLog?.(e)};if(d(`[permissions-service] shouldBlockMcp: toolName="${a}", providerIdentifier="${c}"`),await this.isComputerUseDisabledByAdminFor(c))return d(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${a}", providerIdentifier="${c}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,c,a))return d(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${a}", providerIdentifier="${c}"`),{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=cP({server:aP(c),tool:a});let b,S,k;switch(w.kind){case"block":return d(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${a}", providerIdentifier="${c}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${a}", providerIdentifier="${c}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${a}", providerIdentifier="${c}"`),!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?(d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0}):(d(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${a}", providerIdentifier="${c}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:c,toolName:a,annotations:u}):k&&await this.isMcpExplicitlyAllowed(e,c,a))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:a,...Ox(r,u),providerIdentifier:c,args:l,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(c),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:c,toolName:a,annotations:u});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,c,a);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${a}", providerIdentifier="${c}"`),!1;d(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${a}", providerIdentifier="${c}"`)}return d(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${a}", providerIdentifier="${c}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${a}`,approvalDetails:{type:"mcp",name:s,toolName:a,...Ox(r,u),providerIdentifier:c,args:l,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Ix(o)}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(aP(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=ox(e.meta?.["cursor/computerUseScope"])??ox(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])=>nx(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&&ix.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?QE(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&&ix.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:QE(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 JE(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":ZE.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.":XE.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=ex(o.app.bundleId)?void 0:cP({server:r.serverId,tool:tx(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=aP(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(aP(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||ex(e)?void 0:cP({server:this.computerUse.serverId,tool:tx(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??kC(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=aP(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}){Tx.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&&OE(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&&function(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=NE(e);return 0!==r.length&&t.some((e=>NE(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}(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 hP=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 pP=65536,fP=1048576,mP=(0,C.h)("LocalReadExecutor"),gP=async(e,t,r,n)=>{const o=setTimeout((()=>{mP.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function wP(e){return BigInt(Math.min(e,4294967295))}async function yP(e,t){if(0===t)return(0,Ys.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Ys.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function SP(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 kP=Buffer.from("\n---\n");function _P(e,t){const r=e.length;if(r<2*kP.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(kP,r-kP.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+kP.length,r-4).toString("utf-8"))?o:r}const CP=[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 EP(e){return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:e,reason:"File content is binary data, not text"})}})}function xP(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=PP(s,e),c=PP(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function PP(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 IP(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function RP(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 TP(e,t,r){const n=RP((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 AP(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=IP(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=fi(c,o)),{text:c,truncated:l}}function $P(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=IP(e.slice(t,o));const i=s.length>n||on&&(s=fi(s,n)),s.lengthn?{text:e.text+fi(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function DP(e,t){if(e.truncated)return e;const r=MP(e,t);return{text:r.text,truncated:r.truncated}}function OP(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=MP(n,"\n")),n=MP(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function FP(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 NP(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Yt:Math.min(Yt,e.maxChars+2)}function jP(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 LP extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function UP(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return BP(r)>t?t:0}return 0}function BP(e){return e>=240?4:e>=224?3:e>=192?2:1}class WP{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 LP}validate(e){let t=e;if(this.carry.length>0){const r=BP(this.carry[0]??0)-this.carry.length;if(e.length0?Math.min(t,fP):fP,o=await yP(e,r);return o.length===t&&(0,n.isUtf8)(o)||Ia(new ha.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===fP&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function zP(e){const t=await(0,Ys.stat)(e),r=await lc(e);if(r.isBinaryFile)return;const n=HP({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await qP(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function GP(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,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,j=0,L=!1,U=!1;const B=e=>{let t=e;return!L&&t.length>0&&(L=!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>=Yt,q=()=>v||w&&g>=Yt,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Yt-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:fi(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=Yt-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:fi(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++:j++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.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===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t1&&A>Yt;)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-UP(e));return Q=new WP(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 ha.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,ti.createReadStream)(t,{highWaterMark:pP,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 LP;throw e}return}const i=(0,ti.createReadStream)(t,{highWaterMark:pP,signal:e.signal,...s}).pipe(pa.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=DP(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&&vc(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)+pP,ae=e=>e.text.length>ie?{text:fi(e.text,ie),truncated:!0}:e,ce=()=>OP({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(OP({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class VP{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}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,i.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new tr.sV({result:{case:"error",value:new tr.F_({path:o,error:Si})}});const a=(0,bi.o1)(o,this.workspacePath),c=await gP(e,"permissionsService.shouldBlockFileRead",3e3,(()=>iP(this.permissionsService,a)));if(c){const r=await gP(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await hu(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:$w.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"}}(c,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new tr.sV({result:{case:"rejected",value:new tr.f4({path:a,reason:r.reason??""})}});if("denied"===r.kind)return new tr.sV({result:{case:"permissionDenied",value:new tr.lW({path:a})}})}void 0!==this.mcpStateAccessor&&_E(e,this.mcpStateAccessor,a);try{const r=await gP(e,"stat",3e3,(()=>(0,Ys.stat)(a)));if(r.isDirectory())return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=rr(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)}(a),i=function(e){const t=rr(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(a);if(o||i)return await this.readTerminalFile(e,a,r,t,i&&!o);const c=await gP(e,"getFormatForFile",3e3,(()=>lc(a))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(a),d=nc(a);if(l){const t=await gP(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await bC(e)}catch(t){const r=await SC(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await SC(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Ys.readFile)(a))));return"undecodable"===t.kind?new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,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 tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t.image.data},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(u){const t=await gP(e,"readPdfBinary",3e3,(()=>(0,Ys.readFile)(a)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await gP(e,"readBinaryFile",3e3,(()=>(0,Ys.readFile)(a)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(c.isBinaryFile)return EP(a);{const n=this.useStreamingRead,o=!n||await gP(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Yt){const n=await gP(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=HP(t,r.encodingHint);try{return await GP(e,t,r,o,n)}catch(o){if(o instanceof LP)return await GP(e,t,r,await qP(t.file,t.stats.size),n);throw o}}(e,{file:a,stats:r,format:c},t,o)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"content",value:jP(n.content,n.truncated,t)},totalLines:n.totalLines,fileSize:wP(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await gP(e,"readText",3e3,(()=>sc(a,t.encodingHint))),i=await gP(e,"countLines",3e3,(()=>ma(s))),l=function(e,t,r){const n=xP(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:TP(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,i,t);let u=l.content,d=!1;const h=NP(t);return u.length>h&&(u=jP(u.substring(0,h),!0,t),d=!0),u.lengthyP(t,r.size)));if(o&&(i=s,CP.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return EP(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=vP(e),o=_P(e,n);if("utf-8"!==SP(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=RP((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=$P(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=vP(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=RP((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=AP(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,NP(n));return new tr.sV({result:{case:"success",value:new tr.mE({path:t,output:{case:"content",value:jP(a.content,a.truncated,n)},totalLines:a.totalLines,fileSize:wP(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function KP(e){return Buffer.from(e,"utf16le").toString("utf16le")}var JP=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},ZP=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 XP(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 QP(e){return`Path '${e}' is neither a file nor a directory`}async function YP(e){const t=await(0,Ys.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function eI(e,t,r){const n=function(e,t){let r;for(const n of t)(0,bi.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 tI extends Error{}function rI(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function nI(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 oI(e){switch(e){case"content":return new oy.vD({result:{case:"content",value:new oy.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new oy.vD({result:{case:"files",value:new oy.T7({ripgrepTruncated:!0})}});case"count":return new oy.vD({result:{case:"count",value:new oy.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function sI(e,t){let r=Buffer.concat(e);t&&(r=r.subarray(0,r.lastIndexOf(10)+1));const n=r.toString("utf8");return n.includes("�")?{stdout:n,stdoutBytes:r}:{stdout:n}}function iI(e){return/^(utf-?16|ucs-?2)/i.test(e)}const aI=(0,C.h)("local-exec/grep"),cI=(0,E.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"]}),lI=(0,E.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"]});function uI(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function dI(e){try{return(0,ti.existsSync)(e)}catch{return"check_failed"}}function hI(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function pI(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 fI(e,t,r,n){return{...gI(e),...n,cwd:t,cwdExists:dI(t),errorMessage:tl(r),errorCode:el(r),errno:hI(r),syscall:pI(r,"syscall"),errorPath:pI(r,"path")}}function mI(e){return new Error(`Path does not exist: ${e}`)}function gI(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,ti.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,ti.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,ti.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,ti.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,ti.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,ti.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,ti.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 e=r.concat("node_modules.asar");try{t.asarExists=(0,ti.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,ti.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,ti.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class wI{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;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}computeRelativeTarget(e,t){const r=(0,bi.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,bi.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,bi.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,bi.o1)(t.path,this.singleWorkspacePath??e);return(0,bi.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 Mc(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,Ys.stat)(e)).isFile())return;const{encoding:t}=await lc(e);return iI(t)?t.toLowerCase():void 0}catch{return}}((0,bi.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,bi.o1)(s.file,t),i=await al(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 xE(t,(e=>(0,bi.o1)(n(e),r)));return s.statTimedOut&&(aI.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),lI.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,wI.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),p=await this.buildArgs(t,r,"files_with_matches",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?wI.HARD_MAX_OUTPUT_LINES:wI.CLIENT_LIMIT_LINES,d=wI.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 sy;let s=0,i=0,a=0;for(;iy(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(l,u,d)),g=m.totalFiles>wI.CLIENT_LIMIT_LINES;let w=m.files;n&&(w=await this.keepNewestPage(h.ctx,w,t,(e=>e),a),g&&(w=w.join("\0").split("\0")));const y=(await this.filterBlockedFiles(w.map((e=>({file:e}))),t)).map((({file:e})=>e)),v=w.length-y.length,b=new oy.T7({files:y,totalFiles:uy(m.totalFiles-v),clientTruncated:g,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new oy.vD({result:{case:"files",value:b}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}var l,u,d}async runCountMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),p=await this.buildArgs(t,r,"count",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?wI.HARD_MAX_OUTPUT_LINES:wI.CLIENT_LIMIT_LINES,d=wI.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 sy;let i=0;for(;iy(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}}(l,u,d)),g=n?await this.keepNewestPage(h.ctx,m.counts,t,(e=>e.file),a):m.counts,w=await this.filterBlockedFiles(g,t),y=w.reduce(((e,t)=>e+t.count),0),v=g.length-w.length,b=g.reduce(((e,t)=>e+t.count),0)-y,S=new oy.xA({counts:w.map((e=>new oy.sS({file:e.file,count:uy(e.count)}))),totalFiles:uy(m.totalFiles-v),totalMatches:uy(m.totalMatches-b),clientTruncated:m.totalFiles>wI.CLIENT_LIMIT_LINES,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new oy.vD({result:{case:"count",value:S}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}var l,u,d}async runContentMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const l=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),u=await this.buildArgs(t,r,"content",n),d=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,h=wI.CLIENT_LIMIT_LINES*(d?2:1),p=await this.executeRg(l.ctx,t,u,h,o,s,a);this.throwOnRipgrepFailure(p,t,r);const f=await this.decodeLinesAsRead(l.ctx,p,t,a),{byFile:m,totalLines:g,totalMatchedLines:w,clientTruncated:y,ripgrepTruncated:v}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return JP(o,(0,i.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 sy;let a=0,c=0,l=0,u=0;for(;iy(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:uy(l),totalMatchedLines:uy(a),totalFiles:uy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{ZP(o)}}(f,wI.CLIENT_LIMIT_LINES,h,l.ctx),b=Array.from(m.values()),S=await this.filterBlockedFiles(b,t),k=b.filter((e=>!S.includes(e))),_=k.reduce(((e,t)=>e+t.matches.length),0),C=k.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),E=n?await this.orderNewestFirst(l.ctx,S,t,(e=>e.file),a):S,x=new oy.Zp({matches:E.map((e=>new oy.uI({file:e.file,matches:e.matches.map((e=>new oy.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:uy(g-_),totalMatchedLines:uy(w-C),clientTruncated:y,ripgrepTruncated:v||p.timedOut||p.stdoutByteCapped});return{result:new oy.vD({result:{case:"content",value:x}}),timedOut:p.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const a=t.stdoutBytes;if(void 0===a)return t.stdout;const c=JP(s,(0,i.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),l=function(e,t){const r=[],o=new sy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&iy(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)))],d=new Map,h=performance.now()+wI.LINE_ENCODING_TIMEOUT_MS;let p=0;for(;p{let d=!1,h=!1;const p=()=>{h||(h=!0,c.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(wI.ripgrepTimeoutError());let f;try{const e=s;f=(0,ri.spawnInSandbox)((0,ri.Ko)(),r,{cwd:t},e),0}catch(r){if(p(),uI(r)){const n=(0,ri.Ko)();if(aI.error(e,"rg_diagnostics.spawn_throw",void 0,fI(n,t,r,a)),!1===dI(t))return u(mI(t))}return u(r)}const m=[],g=[];let w=0,y=0,v=0,b=!1,S=!1;const k=()=>{if(!d)try{p();const e=sI(m,!0);""===e.stdout?u(wI.ripgrepTimeoutError()):i({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:S}),f.kill()}catch{}};o.addEventListener("abort",k,{once:!0});const _=()=>{o.removeEventListener("abort",k),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",_,{once:!0}),f.stdout?.on("data",(e=>{if(!S&&!b)if(w+=e.length,w>l){S=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,b=!0;try{f.kill()}catch{}break}v+=r;const o=t>=0?e.subarray(0,t):e;m.push(o)}else m.push(e)})),f.stderr?.on("data",(e=>{y+=e.length,y<=l&&g.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_),p(),uI(r)){const n=(0,ri.Ko)();if(aI.error(e,"rg_diagnostics.spawn_enoent",void 0,fI(n,t,r,a)),!1===dI(t))return void u(mI(t))}u(r)})),f.on("close",(t=>{d=!0,o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_);const r=sI(m,S),n=Buffer.concat(g).toString("utf8");p(),i({...r,stderr:n,exitCode:t??0,timedOut:!1,stdoutByteCapped:S})}))}))}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 al(t[0]);return null===r?{error:XP(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await YP(t[0])?{error:QP(e)}:{resolvedTarget:r}}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const a=JP(n,(0,i.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(o=l)&&"files_with_matches"!==o&&"count"!==o)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c},h=Gi(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,bi.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new oy.Ud({result:{case:"error",value:new oy.ts({error:bi.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 oy.Ud({result:{case:"error",value:new oy.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&_E(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,bi.BJ)(s,o))continue;const i=await al(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await YP(s))return new oy.Ud({result:{case:"error",value:new oy.ts({error:QP(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&_E(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:XP(m.path);return new oy.Ud({result:{case:"error",value:new oy.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?rI(wI.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=oI(u),n++,o=!0;continue}if(!1===dI(s))return new oy.Ud({result:{case:"error",value:new oy.ts({error:`Path does not exist: ${s}`})}});const i=t??rI(wI.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 tI))throw t;if(r[s]=oI(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(nI));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw wI.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=>eI(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 oy.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 oy.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 oy.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new oy._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,bi.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new oy.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,bi.o1)(m.path,this.singleWorkspacePath);try{await(0,Ys.stat)(e)}catch(t){return new oy.Ud({result:{case:"error",value:new oy.ts({error:`Path does not exist: ${e}`})}})}}return new oy.Ud({result:{case:"error",value:new oy.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{ZP(n)}var o}}wI.MAIN_TIMEOUT_MS=25e3,wI.INDEXED_GREP_TIMEOUT_MS=25e3,wI.INDEXED_GREP_CONTEXT_TIMEOUT_MS=wI.INDEXED_GREP_TIMEOUT_MS+100,wI.HARD_MAX_OUTPUT_LINES=1e4,wI.CLIENT_LIMIT_LINES=2e3,wI.LINE_ENCODING_TIMEOUT_MS=2e3,Nn.object({record_v:Nn.number().int().nullish(),pid:Nn.number().int().nonnegative().nullish(),version:Nn.string().nullish(),started_at:Nn.number().nullish(),control_sock:Nn.string().nullish(),runtime_dir:Nn.string().nullish(),data_dir:Nn.string().nullish(),config_path:Nn.string().nullish(),log_path:Nn.string().nullish(),metrics_addr:Nn.string().nullish(),exe:Nn.string().nullish()}),Nn.object({mountpoint:Nn.string().nullish(),capabilities:Nn.array(Nn.string()).nullish(),nfs_transport:Nn.string().nullish(),bind_ignored:Nn.object({active:Nn.array(Nn.string()).nullish()}).passthrough().nullish()}),Nn.object({daemon_alive:Nn.boolean().nullish(),mounts:Nn.array(Nn.unknown()).nullish(),data_plane:Nn.object({enabled:Nn.boolean().nullish()}).passthrough().nullish()});const yI=Nn.number().int().nonnegative(),vI=Nn.object({line_no:Nn.number().int().positive(),kind:Nn.enum(["match","before","after"]),text:Nn.string().optional(),bytes:Nn.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Nn.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Nn.object({type:Nn.literal("file"),path:Nn.string(),lines:Nn.array(vI)}),Nn.object({type:Nn.literal("summary"),files_searched:yI,more:Nn.boolean(),stop_reason:Nn.string().nullable(),skipped:Nn.object({over_size:yI,size_unknown:yI,budget_exhausted:yI,fetch_failed:yI,unreadable:yI})}),Nn.object({type:Nn.string()}),(0,C.h)("local-exec/grove-grep");var bI=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),SI=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},kI=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 _I{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{SI(r,(0,i.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,bi.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Ys.stat)(n)}catch(e){return"ENOENT"===el(e)?function(e){const t=rr(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:"No active terminals."})}}):new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:`Path does not exist: ${n}`})}}):new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:tl(e)})}})}if(!r.isDirectory())return new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Gi(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 bI.fv({result:{case:"timeout",value:new bI.ze({directoryTreeRoot:a})}}):new bI.fv({result:{case:"success",value:new bI.PC({directoryTreeRoot:a})}})}catch(e){return new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{kI(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return SI(o,(0,i.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{kI(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const a={stack:[],error:void 0,hasError:!1};try{SI(a,(0,i.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const c=(0,s.resolve)(t),l=new bI.vq({absPath:c,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(c,l);const d={charactersUsed:c.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=Fc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,s.resolve)(t,e),n=await al(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,c,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){a.error=e,a.hasError=!0}finally{kI(a)}}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 bI.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]=uy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=uy(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 bI.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)}}var CI=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 EI=1e4,xI=5e3,PI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class II{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,tEI&&(this.fullOutput="")}getOutput(){return this.totalChars<=EI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=EI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class RI{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=_i-this.kept.length;this.full=e.length>=t,this.kept+=fi(e,t)}get text(){return this.kept}}function TI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class AI{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 xr.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new xr.QR(o)};return new xr.W4({result:i,sandboxPolicy:Vi(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,ri.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new II,a=new RI,l=new RI;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,ri.ue)((0,ri.Xw)({...process.env,...PI,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,Sl.D9)(bl.spawn,y.executable,y.args,w):(0,ri.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:dy(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=xr.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=xr.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:TI(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,i.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,i.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,bi.o1)(t.workingDirectory||this.defaultCwd),a=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let c=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId},c);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new xr.W4({result:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new xr.W4({result:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:s,reason:pu(l.reason)})}});c=l.policy,Di()&&(c=Ui(o,t.parsingResult)),c&&"insecure_none"!==c.type&&(c={...c,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:c,timeoutMs:a});return this.buildResult({args:t,workingDirectory:s,processResult:u,sandboxPolicy:c})}catch(e){r.error=e,r.hasError=!0}finally{CI(r)}}}var $I=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MI(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DI{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:MI(t.cursor),advance:!1!==t.advance});return new $I.Ev({result:{case:"success",value:new $I.iS({events:e.events.map((e=>new $I.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 $I.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $I.Ev({result:{case:"error",value:new $I.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OI{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Cr.nt({result:{case:"error",value:new Cr.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Cr.nt({result:{case:"success",value:new Cr.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class FI{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,P.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 NI(e,t){return`${e}:${(0,Js.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function jI(e,t){const r=new ei.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=NI(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 LI=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),UI=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class BI{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"),WI(HI(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),WI(new LI.GL({result:{case:"success",value:new LI.uX({path:t.path,diagnostics:e.map(qI)})}}),await o))}catch(e){return r("unavailable"),WI(HI(t.path,e instanceof Error?e.message:String(e)),await o)}}}function WI(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function HI(e,t){return new LI.GL({result:{case:"error",value:new LI.HW({path:e,error:t})}})}function qI(e){return new UI.oQ({severity:zI(e.severity),range:new yl.Q6({start:new yl.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new yl.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function zI(e){switch(e){case 1:return UI.h_.ERROR;case 2:return UI.h_.WARNING;case 3:return UI.h_.INFORMATION;case 4:return UI.h_.HINT;default:return UI.h_.UNSPECIFIED}}class GI{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 UI.Ek({result:{case:"success",value:new UI.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new UI.Ek({result:{case:"error",value:new UI.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new UI.Ek({result:{case:"error",value:new UI.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{VI(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 UI.oQ({severity:this.convertSeverity(e.severity),range:e.range?new yl.Q6({start:new yl.yX({line:e.range.start.line,column:e.range.start.character}),end:new yl.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 UI.h_.ERROR;case 2:return UI.h_.WARNING;case 3:return UI.h_.INFORMATION;case 4:return UI.h_.HINT;default:return UI.h_.UNSPECIFIED}}}async function JI(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 Qw().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 ZI(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 ZI(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 ZI{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 XI=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]=eR(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=rR(e)}],[/^\+\+\+\s/,e=>{u(),n.to=rR(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},QI=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,YI=/^(a|b|i|w|c|o|1|2)\//,eR=e=>{const t=e?.match(QI);return t?.map((e=>e.replace(YI,"").replace(/("|')$/,"")))},tR=/^\\?['"]|\\?['"]$/g,rR=e=>{let t=nR(e,"-+").trim();return t=sR(t),t.replace(tR,"").replace(YI,"")},nR=(e,t)=>{if(e=aR(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=iR(t);return e.replace(new RegExp(`^${r}+`),"")},oR=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,sR=e=>{const t=oR.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},iR=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${aR(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,aR=e=>`${e??""}`,cR=(0,C.h)("local-mercurial-diff"),lR=5242880,uR="0000000000000000000000000000000000000000";let dR,hR;async function pR(e,t,r={}){const n=await async function(){if(void 0===dR&&(dR=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 Ys.stat(t)).isFile())continue;return"win32"!==process.platform&&await Ys.access(t,ti.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===dR){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return dR}();return await new Promise(((o,s)=>{const i=(0,bl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new xc.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"}`))}}))}))}async function fR(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Ys.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!==hR)return hR;const e=await Ys.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await pR(e,["help","environment"]);hR=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){hR=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Ys.rm(e,{recursive:!0,force:!0})}return hR}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await pR(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Ys.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function mR(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 gR(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 wR(e){const t=s.default.resolve(e);try{return await Ys.realpath(t)}catch{return t}}function yR(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 vR(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function bR({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await pR(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>lR?"":pR(e,["cat","-r",t,"--",r])}async function SR(e,t,r){const n=function(e){switch(e){case Fn.ek.NAME_STATUS:return Fn.ek.NAME_STATUS;case Fn.ek.NAME_STATUS_AND_NUMSTAT:return Fn.ek.NAME_STATUS_AND_NUMSTAT;case Fn.ek.FILE_DIFFS:return Fn.ek.FILE_DIFFS;case Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Fn.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await pR(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){vR(t),r.push("log");const n=(await pR(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===uR)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await pR(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==uR)return n;const o=(await pR(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==uR)return o;const s=(await pR(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:uR}({cwd:t,baseRef:r.baseRef,commands:o});else if(vR(r.baseRef),o.push("log"),a=(await pR(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(vR(r.ref),o.push("log"),c=(await pR(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 pR(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Fn.o$({diffs:XI(t).map((e=>function(e){const t=new Fn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Fn.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:Fn.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 pR(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 Ys.stat(r);if(n.size>lR){const t=await async function(e){const t=(0,Js.createHash)("sha256"),r=await Ys.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 Ys.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 Fn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=yR(e.contents);if(0===t.length)return new Fn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Fn.QP({from:"/dev/null",to:e.path,chunks:[new Fn.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!==Fn.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Fn.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 bR({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 Ys.stat(e);t.afterFileContents=r.size>lR?"":await Ys.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await bR({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=yR(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,Js.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 pR(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:uR,g=(await pR(t,["status","-0"])).length>0}cR.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Fn.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 cR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return cR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const kR=(0,C.h)("local-git-diff");function _R({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function CR(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 _R(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function ER(e){const t=XI(e);return new Fn.o$({diffs:t.map((e=>function(e){const t=new Fn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Fn.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:Fn.Wf.UNSPECIFIED})}function xR(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:ma(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 PR=["main","master","develop"];async function IR(e,t){const r=s.default.join(e,t),n=await Ys.lstat(r);if(n.isSymbolicLink())return{contents:await Ys.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Ys.readFile(r,"utf8"),path:t,isSymlink:!1}}async function RR(e,t,r){const n=Qw(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await CR(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 wR(t);let n=await wR(e);if(mR(n,r))return;let o=!1;for(;gR(n,r)&&!mR(n,r);){try{if((await Ys.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?fR(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await fR(e)?"none":"mercurial"}(t,o);if(kR.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw kR.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return SR(e,t,r);const a=function(e){switch(e){case Fn.ek.NAME_STATUS:return Fn.ek.NAME_STATUS;case Fn.ek.NAME_STATUS_AND_NUMSTAT:return Fn.ek.NAME_STATUS_AND_NUMSTAT;case Fn.ek.FILE_DIFFS:return Fn.ek.FILE_DIFFS;case Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Fn.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await CR(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of PR){const r=`origin/${t}`;try{return await CR(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await CR(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await CR(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 CR(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=ER(h);else{const t=_R(d);if(r.computePatchId||!await async function(e){return(await CR(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 CR(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),kR.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 CR(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 IR(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${xR([e])}\n\\ No newline at end of file`:await CR(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...ER(t).diffs)}}if(a!==Fn.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Fn.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 CR(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 CR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await IR(t,s.to)).contents}catch{try{s.afterFileContents=await CR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){kR.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 JI({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 CR(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){kR.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,xR(f))):void 0,v=!0===r.returnHeadSha?(await CR(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await CR(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Fn.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 TR{async execute(e,t){return RR(e,t.cwd,t)}}var AR=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class $R{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 AR.M({allowlisted:r})}}var MR=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),DR=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 OR(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function FR(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function NR(e){return e instanceof Error?e.message:String(e)}function jR(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: ${NR(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const LR=(0,ha.promisify)(bl.execFile);class UR{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(!OR(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),UR.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 Ys.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 Ys.mkdir(this.stagingDir,{recursive:!0}),await Ys.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:MR.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:MR.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:MR.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 Ys.rename(e,t)}catch(e){if(!FR(e,"EXDEV"))throw e}try{await Ys.copyFile(e,t)}catch(e){throw await Ys.rm(t,{force:!0}).catch((()=>{})),e}try{await Ys.unlink(e)}catch(e){throw await Ys.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 Ys.open(e,"wx");return await t.close(),e}catch(e){if(!FR(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,Sl.D9)(LR,"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,Sl.D9)(LR,"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:UR.PROXY_TARGET_FPS,includeBrandTag:!0}),await Ys.access(n,Ys.constants.R_OK)}catch(t){const r=(0,i.fU)(e);throw r?.setAttribute("error.type",function(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}(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,Sl.D9)(LR,"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 ${UR.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${UR.PROXY_TARGET_FPS}fps`)}return UR.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Ys.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await Fg(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${UR.DEFAULT_REFRESH_RATE}Hz`),o=UR.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${UR.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${UR.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",UR.PROXY_PRESET,"-crf",String(UR.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,Sl.D9)(bl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.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);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.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);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.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:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,Sl.D9)(bl.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 Ys.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(OR(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{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),FR(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();try{const o=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!OR(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${NR(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await Ys.access(d,Ys.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=FR(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${NR(e)}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:jR(t,r,a,n)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=NR(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:jR(o,r,a,n)})}})}const m={profileVersion:UR.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:UR.PROXY_TARGET_FPS,codec:"h264",profile:UR.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:o,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await Ys.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await Ys.rm(g,{force:!0}).catch((()=>{})),e}try{await Ys.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${NR(e)}`)}return this.clearActiveRecordingIfCurrent(r),new MR.Tj({result:{case:"saveSuccess",value:new MR.ol({path:g,recordingDurationMs:sr.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new MR.Tj({result:{case:"failure",value:new MR.yH({error:NR(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,i.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`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===MR.$u.UNSPECIFIED)return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case MR.$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 Ys.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Ys.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await Fg(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,o);r=a;const l=function(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}(this.display);n=new zg({displayNum:l,resolution:i}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new MR.Tj({result:{case:"startSuccess",value:new MR.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await Ys.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new MR.Tj({result:{case:"failure",value:new MR.yH({error:e instanceof Error?e.message:String(e)})}})}}case MR.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new MR.Tj({result:{case:"failure",value:new MR.yH({error:"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 MR.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!OR(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await Ys.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new MR.Tj({result:{case:"discardSuccess",value:new MR.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await Ys.rm(r,{force:!0,recursive:!0}),n=!0}catch{}this.activeRecording=null;const o=t instanceof Error?t.message:String(t),s=n?"":`. Session may remain at: ${r}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{DR(r)}}}async function BR(e){const t=await(0,Ys.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 BR(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 WR(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(...WR(t,e,s))}))}return n}async function HR(e){if(!await(0,Ys.access)(e,Ys.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await BR(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>WR(e,"",r===t.length-1))).join("\n")}async function qR(e,t){return HR(s.join(e,"agent-notes",t))}async function zR(e){return HR(s.join(e,"agent-notes","shared"))}UR.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,UR.PROXY_TARGET_WIDTH=1920,UR.PROXY_TARGET_FPS=60,UR.PROXY_CRF=17,UR.PROXY_PRESET="veryfast",UR.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",UR.DEFAULT_REFRESH_RATE=60;var GR=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},VR=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 KR=(0,C.h)("local-exec:request-context"),JR=Symbol("sectionLoadTimedOut");async function ZR(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{GR(o,(0,i.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{VR(o)}}async function XR(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 QR(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,ri.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,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Nr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:sr.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 YR={type:"object",properties:{},additionalProperties:!1};function eT(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Ut.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new ds.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?sr.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tT(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 ds.E$({toolName:e.toolName,..._C(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?sr.Value.fromJson(e.inputSchema):void 0}}})));return!Lt(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===UC))||o.push(new ds.E$({toolName:UC,...r?{}:{description:BC,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(YR)}:{inputSchema:sr.Value.fromJson(YR)}}})),new ds.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 ds.U_({enabled:!0,mcpDescriptors:n})}function rT(e){const t=e?.trim();return t||void 0}function nT(e,t){const r=function(e){return rT(e.serverIdentifier)}(e);if(r)return r;const n=rT(e.serverName);return n?t.get(n)??n:void 0}class oT{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(KR.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(KR.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=>nT(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=>nT(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=>(KR.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:zt(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sT(e){return new er._W({result:{case:"success",value:new er.pv({servers:e.servers.map((e=>new er.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new ds.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?sr.Value.fromJson(e.inputSchema):void 0,metaJson:Bt(e._meta),..._C(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iT{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==er.ew.FORCE_IF_MISSING&&t.refreshPolicy!==er.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 sT({...r,servers:n})}return sT(r)}}class aT{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.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:I,isAttributionDisabledByAdmin:R,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=I,this.isAttributionDisabledByAdmin=R,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.onRequestContext=c.onRequestContext,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),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)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,ye.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=GR(r,(0,i.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Vc(n.ctx,this.gitExecutor,t),s=o?await Kc(n.ctx,this.gitExecutor,o):void 0,a={repoPath:o??void 0,remoteUrl:void 0!==s?Jc(s):void 0};this.cachedWorkspaces.set(t,a)}catch(e){r.error=e,r.hasError=!0}finally{VR(r)}}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,ye.q6)(),r=GR(e,(0,i.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)&&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{VR(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GR(t,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},a=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[c,l,u,d]=await Promise.all([a("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),a("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),a("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),a("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-o);return h>1e3&&KR.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...s,ruleCount:c.length}),{rules:[...this.additionalRules,...c],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{VR(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=GR(r,(0,i.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,a=!0;const c=(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 i=o?.[e];if(void 0!==i)return void 0!==r.repoPath&&void 0===i.gitStatus&&(a=!1),new Nr.DS({path:r.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:zc(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:c,branchName:l}=await async function(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(ZR(e,t,r,n)),o(XR(e,t,r,n))]);return{status:s,branchName:i}}(n.ctx,t.gitExecutor,r.repoPath,3e3);return void 0===c&&(a=!1),new Nr.DS({path:r.repoPath,status:c,branchName:l,remoteUrl:r.remoteUrl,isOriginBacked:zc(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:c,gitRepoInfoComplete:s,gitStatusInfoComplete:s&&a}}catch(e){r.error=e,r.hasError=!0}finally{VR(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=GR(n,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,a=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=GR(e,(0,i.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath){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{VR(e)}},c=performance.now(),l={},u=(e,t)=>{const r=performance.now();return t.finally((()=>{l[e]=Math.round(performance.now()-r)}))},d=e=>function(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(JR)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}(e,this.sectionLoadTimeoutMs),h=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),[p,f,m,{gitRepos:g,gitRepoInfoComplete:w,gitStatusInfoComplete:y},v,b,S,k,_,C]=await Promise.all([u("globalCache",d(a())),u("mcpState",d(h((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(o.ctx))))),u("env",QR(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})),u("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),u("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?qR(s,t.notesSessionId):Promise.resolve(void 0)),u("sharedNotes",this.agentNotesEnabled&&s?zR(s):Promise.resolve(void 0)),u("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),u("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),u("agentSkills",d(h((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([]))))),u("adminCommandDenylist",d(h((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))]),E=p===JR,x=f===JR,P=_===JR,I=C===JR,R=E?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:p,T=x?{servers:[]}:f,A=P?[]:_,$=I?void 0:C;(E||x||P||I)&&KR.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:E,mcpState:x,agentSkills:P,adminCommandDenylist:I});const M=performance.now()-c;for(const[e,t]of Object.entries(l))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(M)),M>1e3&&KR.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(M),...l});const D=this.mcpMetaToolEnabled?tT(T,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,O=this.attributionConfigProvider?.get(),F=!k&&(O?.attribution?.attributeCommitsToAgent??!0),N=!k&&(O?.attribution?.attributePRsToAgent??!0),j=new Nr.bb({rules:R.rules,env:m,gitRepos:g,gitRepoInfoComplete:w,repositoryInfo:R.codebaseReference?[{relativeWorkspacePath:R.codebaseReference.relativeWorkspacePath,repoName:R.codebaseReference.repoName,repoOwner:R.codebaseReference.repoOwner,isTracked:R.codebaseReference.isTracked,isLocal:R.codebaseReference.isLocal,orthogonalTransformSeed:R.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:R.codebaseReference.pathEncryptionKey}]:[],...eT(T,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:v,sharedNotesListing:b,customSubagents:R.customSubagents,mcpFileSystemOptions:S,mcpMetaToolOptions:D,supportsMcpAuth:!0,commitAttributionMessage:F?"enabled":void 0,prAttributionMessage:N?"enabled":void 0,agentSkills:A,adminCommandDenylist:$?.rules??[]});return null!==R.cloudRule&&void 0!==R.cloudRule&&(j.cloudRule=R.cloudRule),this.reportSectionCompleteness&&(j.rulesInfoComplete=!E,j.customSubagentsInfoComplete=!E,j.agentSkillsInfoComplete=!P,j.mcpInfoComplete=!x,j.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==S,j.envInfoComplete=!0,j.gitStatusInfoComplete=y),j}catch(e){n.error=e,n.hasError=!0}finally{VR(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=GR(r,(0,i.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 Nr._G({result:{case:"success",value:new Nr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(tl(e)),new Nr._G({result:{case:"error",value:new Nr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{VR(r)}}}function cT(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===xr._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lT=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 uT{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new xr.W4({result:{case:"success",value:new xr.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Vi(e.sandboxPolicy)}):new xr.W4({result:{case:"failure",value:new xr.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Vi(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?{perRepo: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?xr.Lv.TIMEOUT:xr.Lv.USER_ABORT:xr.Lv.UNSPECIFIED:void 0,u=dy(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 xr.W4({result:{case:"timeout",value:new xr.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:Vi(o)}):e.signal.aborted?new xr.W4({result:{case:"rejected",value:new xr.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Vi(o)}):new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:Vi(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,i.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,i.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0,a=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),c=cT(t),l=(0,bi.o1)(a);if(!t.parsingResult)return new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(Hr(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId},s);if("block"===e.kind)return new xr.W4({result:fu(o,l,e.reason)});u=s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:c,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t)},s);if("block"===e.kind)return new xr.W4({result:fu(o,l,e.reason)});u=e.policy}if(Di()&&(u=Ui(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await cl(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,a,c,u)}catch(e){r.error=e,r.hasError=!0}finally{lT(r)}}}var dT=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hT{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new xr.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dT.e({allowlisted:n})}}class pT{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new xr.jK({status:xr.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fT=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 mT=(0,C.h)("local-exec:shell-stream");class gT{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===xr.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:xr.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:xr.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 wT(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yT{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}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,ye.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new xr.jK({status:xr.iA.ACCEPTED,shellResult:o}):new xr.jK({status:xr.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(Rr).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:wT()},""!==e.toolCallId&&e.timeoutBehavior===xr._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,i.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0;const a=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),c=cT(t),l=(0,bi.o1)(a),u=Date.now(),d=new xr.HO(li(o).structured),h=ia({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new xr.FI({event:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:pu(p.reason)})}}));if(mT.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}),Hr(t))mT.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"});else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:l,timeout:c,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wT()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mT.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 xr.FI({event:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=pu(n.reason);return void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:r})}}))}s=n.policy,mT.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}if(Di()&&(s=Ui(o,d)),s&&"insecure_none"!==s.type){const e=await cl(this.ignoreService);s={...s,ignoreMapping:e}}yield new xr.FI({event:{case:"start",value:new xr.tD({sandboxPolicy:Vi(s)})}});const f=t.timeoutBehavior===xr._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?{perRepo:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:a,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()),c));const k=f?new gT(b[Symbol.asyncIterator](),c):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new xr.W4({result:{case:"success",value:new xr.QR({shellId:E,pid:C,command:o,workingDirectory:l,msToWait:dy(Date.now()-u),backgroundReason:xr.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&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 D=k?.iterate()??b;try{for await(const r of D)if("stdout"===r.type)x+=r.data,yield new xr.FI({event:{case:"stdout",value:new xr.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new xr.FI({event:{case:"stderr",value:new xr.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;I=!0,r.aborted&&(n=e.signal?.aborted?xr.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?xr.Lv.TIMEOUT:xr.Lv.USER_ABORT),yield new xr.FI({event:{case:"exit",value:new xr.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:dy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof ri.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mT.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new xr.FI({event:{case:"sandboxUnsupported",value:new xr.rI({command:o,workingDirectory:l,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||I||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===xr.Jg.USER_REQUEST?xr.Jg.USER_REQUEST:xr.Jg.TIMEOUT,s=n===xr.Jg.USER_REQUEST?Date.now()-u:c;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:l,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new xr.FI({event:{case:"backgrounded",value:new xr.Y9({shellId:r,command:o,workingDirectory:l,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new xr.FI({event:{case:"exit",value:new xr.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:xr.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{fT(n)}}}const vT={kind:"absent"};class bT{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 ei.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(xT(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=xT(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=xT(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=xT(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=xT(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=xT(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}async function ST(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await ET(t);const r=await _T(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}class kT{constructor(e,t,r,n){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n}async execute(e,t,r){const n=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,bi.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===n)return this.inner.execute(e,t,r);const o=this.reads.begin(n);try{let s,i;try{s=await iP(this.permissionsService,n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}if(!1!==s&&"needsApproval"!==s.type)return await this.readAndForget(e,t,r,n,o);if(!1!==s){const s=await this.inner.execute(e,t,r),i=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await _T(t)}catch{return}}(s,n.resolvedPath);return this.commit(n,o,s,i),s}try{i=await _T(n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}const a=await this.inner.execute(e,t,r);return this.commit(n,o,a,i),a}finally{this.reads.end(n,o)}}commit(e,t,r,n){"fileNotFound"!==r.result.case?void 0===n||"success"!==r.result.case||"content"!==r.result.value.output.case?this.reads.forget(e,t):this.reads.record(e,{kind:"fingerprint",...n},t):this.reads.record(e,vT,t)}async readAndForget(e,t,r,n,o){const s=await this.inner.execute(e,t,r);return this.reads.forget(n,o),s}}async function _T(e){try{const t=await(0,Ys.stat)(e);if(!t.isFile()||t.size>Yt)return}catch(e){return PT(e)}let t;try{t=await(0,Ys.open)(e,function(){const e=ti.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Yt)return;const n=(0,Js.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Yt;){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>Yt)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return PT(e)}finally{await(t?.close())}}function CT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}async function ET(e){try{return await(0,Ys.stat)(e),!0}catch(e){if(IT(e))return!1;throw e}}function xT({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function PT(e){if(!IT(e))throw e}function IT(e){const t=el(e);return"ENOENT"===t||"ENOTDIR"===t}var RT=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class TT{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new RT.M({allowlisted:r})}}var AT=r("node:constants");class $T extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}const MT=new ha.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),DT=new Map([["€",128],["‚",130],["ƒ",131],["„",132],["…",133],["†",134],["‡",135],["ˆ",136],["‰",137],["Š",138],["‹",139],["Œ",140],["Ž",142],["‘",145],["’",146],["“",147],["”",148],["•",149],["–",150],["—",151],["˜",152],["™",153],["š",154],["›",155],["œ",156],["ž",158],["Ÿ",159]]),OT=new Set([194,195,226,239]),FT=/\p{Lu}/u,NT=new Set([" ","­","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),jT=new Set(["¿","¡"]),LT=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,jT],[209,jT],[211,jT],[218,jT],[220,jT]]),UT=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),BT=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function WT(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:DT.get(e)}function HT(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&&FT.test(e[t-1]))return}else{if(NT.has(s))return;if(!0===LT.get(r)?.has(s))return;if(3===n&&UT.has(s)&&NT.has(e[t+2]))return}let i;try{i=MT.decode(o)}catch{return}return BT.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function qT(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=HT(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const zT=["mojibake","replacement_chars"];function GT(e){return e<=1?"1":e<6?"2-5":"6+"}function VT(e){return e<=0?"0":GT(e)}function KT(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=eA(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function JT(e,t){return e<=t?"existing_only":"new_damage"}function ZT(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(qT(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return qT(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 XT(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function QT(e,t,r){const n=qT(r,1e3);if(0===n.length)return XT("mojibake");const o=void 0===e?[]:qT(e,Math.max(n.length,6));return{detector:"mojibake",outcome:JT(n.length,o.length),file:KT(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:ZT(n,o)}}function YT(e,t,r){const n=Ra(r);if(0===n)return XT("replacement_chars");const o=void 0===e?0:Ra(e);return{detector:"replacement_chars",outcome:JT(n,o),file:KT(e,o,t),afterCount:n,beforeCount:o}}function eA(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 tA=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 rA(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":tA.get(t)??"other"}const nA=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function oA(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:nA.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function sA(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:rA(t.path),encoding:eA(t.encoding),code_page:oA(t.pages),run_count:GT(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":VT(n)),before_count:VT(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}var iA=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 aA=(0,C.h)("LocalWriteExecutor"),cA=(0,E.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"]}),lA=async(e,t,r,n)=>{const o=setTimeout((()=>{aA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function uA(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function dA(e){try{return(await(0,Ys.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===el(e))return"missing";throw e}}async function hA(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await dA(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Ys.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 uA(e)}class pA{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,onWriteForAiTracking:i,writeFileMutationGuard:a,toolCallReads:c}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.onWriteForAiTracking=i,this.writeFileMutationGuard=a,this.toolCallReads=c}async execute(e,t){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Bp.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const r=(0,bi.o1)(t.path,this.workspacePath),n=this.toolCallReads,o=void 0!==n&&""!==t.toolCallId?n.take({toolCallId:t.toolCallId,resolvedPath:r}):void 0,s={writeStarted:!1},i=()=>{void 0===o||s.writeStarted||n?.restore(o)};try{const n=await this.executeWithRecord(e,t,r,o?.recorded,s);return gA(n)&&i(),n}catch(e){throw i(),e}}async executeWithRecord(e,t,r,n,o){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,i.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=fx(r,["assets","agent-tools","swarm-agents"]);if((0,bi.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:bi.PS})}});let h,p,f=!1;try{if((await(0,Ys.stat)(r)).size<=Ci){const e=await lA(c,"readText before write",3e3,(()=>ic(r,t.encodingHint)));h=e.text,p=e.encoding}else f=!0}catch{}const m=(await wx(r)).resolvedPath,g=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await lA(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,m,l)));if(g){const e=await lA(c,"handleBlockReason",3e3,(()=>hu(g,{onNeedsApproval:async(e,o)=>{const s="fileEdit"!==o?.type||o.isNewFile,i="fileEdit"===o?.type?o.diffString:l,a="fileEdit"===o?.type?o.blockReason:void 0;if(await ST(n,m))return fA(r);const c=await this.pendingDecisionProvider.requestApproval({type:$w.Write,details:{path:r,reason:e,isNewFile:s,diffString:i,before:h,after:l,blockReason:a},toolCallId:t.toolCallId});return c.approved?null:new Pr.v3({result:{case:"rejected",value:new Pr.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new Pr.v3({result:{case:"rejected",value:new Pr.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const w=await lA(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Ys.stat)(e)).isFile())return;const n=await(0,Ys.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!==w)return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:w})}});const y=(0,s.dirname)(m);if(await async function(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await ET(t)}catch{return!1}}(n,y))return fA(r);try{await lA(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=await hA(e,t),i=0;for(;ir)throw uA(e);try{await(0,Ys.mkdir)(a,{recursive:!1})}catch(r){const n=el(r);if("EEXIST"===n){if("directory"!==await dA(a))throw r;i+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(a);if(n===a||"missing"!==await dA(n))throw r;o=await hA(e,t),i=0;continue}throw r}i+=1}}(y)))}catch(e){const t=el(e);return"EACCES"===t||"EPERM"===t?new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:y,operation:"create_directory",error:"Permission denied"})}}):new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:tl(e)})}})}let v,b,S;if(void 0!==u)v=u,b=0;else{const e=await lA(c,"getBufferForWrite",3e3,(()=>cc(r,l,this.workspacePath,t.encodingHint)));v=e.buffer,b=e.lines,S=e.format.encoding}const k=()=>lA(c,"writeFile",3e3,(async()=>{if(await ST(n,m))throw new Error(CT(r));let e;c.signal.throwIfAborted(),o.writeStarted=!0,await async function(e,t,r){let n;try{n=await(0,Ys.open)(e,function(){const e=ti.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=el(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof ti.constants.O_NOFOLLOW}(t))throw new $T(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,ti.realpathSync)(e)}catch{throw new $T(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new $T(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new $T(e,`Refusing to write to non-regular file at ${e}`);await n.truncate(0);const s=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i{try{await k()}catch(e){throw _=e,C=!0,e}};try{void 0===this.writeFileMutationGuard?await k():await this.writeFileMutationGuard.runExclusive(m,E)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!C||e!==_))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof $T)return new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=el(e);return"EACCES"===t||"EPERM"===t?new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===el(e)?new Pr.v3({result:{case:"noSpace",value:new Pr.bM({path:r})}}):"EDQUOT"===t?new Pr.v3({result:{case:"error",value:new Pr.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 Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:tl(e)})}})}if(this.fileChangeTracker&&void 0===u&&!d&&!f){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(r,h,l,e)}if(this.onWriteForAiTracking&&void 0===u&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:h,afterContent:l,metadata:e})}catch(e){aA.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const x=v.byteLength;let P;if(void 0!==u||f||d||this.recordEncodingChecks(c,r,h,p,l),t.returnFileContentAfterWrite)try{P=await lA(c,"readText after write",3e3,(()=>sc(r,t.encodingHint)))}catch{}return new Pr.v3({result:{case:"success",value:new Pr.j6({path:r,linesCreated:b,fileSize:x,...void 0!==P&&{fileContentAfterWrite:P}})}})}catch(e){a.error=e,a.hasError=!0}finally{iA(a)}}recordEncodingChecks(e,t,r,n,o){try{const s={path:t,encoding:n,pages:$l.pages()};for(const t of function(e,t,r){return[QT(e,t,r),YT(e,t,r)]}(r,n,o))cA.increment(e,1,sA(t,s))}catch(t){for(const t of zT)cA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});aA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}}}function fA(e){return new Pr.v3({result:{case:"error",value:new Pr.QM({path:e,error:CT(e)})}})}class mA extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function gA(e){return"error"===e.result.case&&e.result.value.error===CT(e.result.value.path)}const wA=(0,C.h)("local-exec:provider"),yA=new Set,vA=new ml.AsyncLocalStorage;class bA extends te{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of yA)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of yA)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,ti.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,ri.$6)(n);return(0,ri.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.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,ri.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});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 lu(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,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new du(c,this.askpassConfig)),this.shellManager&&(c=new uu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uT(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(Ir,jI(l)),this.register(_r,jI(new AI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bT,d=e.overrideWriteExecutor??new pA(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u});this.register(Tr,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(gA(e))throw new mA(e);return e}))},jI(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof mA)return e.result;throw e}}}}(d));const h=e.overrideDeleteExecutor??new Dw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking);this.register(ge,jI(h)),this.register(ve,jI(new Lw)),this.register(be,new TR);const p=this.mcpStateAccessor??new oT(this.mcpLease),f=e.overrideGrepExecutor??new wI(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:p,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep});this.register(Se,jI(f));const m=e.overrideReadExecutor??new kT(new VP(this.permissionsService,a,{mcpStateAccessor:p,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),u,this.permissionsService,a),g=new cr(m);this.register(lr,g),e.registerRedactedReadExecutor&&this.register(ur,g);const w=e.overrideLsExecutor??new _I(this.permissionsService,this.ignoreService,a);this.register(Dt,jI(w)),this.register(we,jI(new KI(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(fe,jI(new BI(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Gt,jI(new kr(new uE(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(lr))))),this.register(Vt,jI(new dE(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Kt,jI(new hE(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(Jt,jI(new iT(p,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const y=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(p,t,e),v=jI({execute:(e,t,r)=>{const n=vA.getStore();return void 0!==n&&(n.ran=!0),y.execute(e,t,r)}});this.register(Fr,{execute:async(t,r,n)=>{const o={ran:!1},s=await vA.run(o,(()=>v.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 p.getState(t),l=eT(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tT(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=[],wA.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Tu(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(le,jI(this.backgroundShellExecutor)),this.shellStreamExecutor=new yT(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(Rr,function(e,t){const r=new ei.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=NI(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new FI(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor)),void 0!==e.agentStoreConflictDrainer&&this.register(ae,new DI(e.agentStoreConflictDrainer)),this.register(jr,new hT(this.permissionsService)),this.register(Zt,new $R(this.permissionsService)),this.register(_n,new TT(this.permissionsService));const b=new pT(this.shellStreamExecutor);this.register(Lr,jI(b));const S=!1===e.enableWriteBackgroundShellStdin?new OI((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OI(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(ue,jI(S)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(me,jI(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new UR({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Or,jI(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aT(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,bi.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,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,onRequestContext:r.onRequestContext});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,yA.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}getRecordScreenExecutor(){return this.recordScreenExecutor}withPendingShells(e){return new re(e,[Y(Rr,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.rebuildRequestContextOnRulesChange&&(yA.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 SA(e){return e.replace(/\\/g,"/")}function kA(e,t){for(const r of t){const t=SA(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var _A;function CA(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return _A.Plugin;const n=SA(e.fullPath);return kA(n,r.builtinDirs)?_A.Builtin:Um(e.fullPath,t).inAgentStore?_A.UserStore:kA(n,r.userDirs)?_A.UserHome:(kA(n,r.workspaceDirs),_A.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"}(_A||(_A={}));var EA=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 xA=(0,ha.debuglog)("merged-agent-skills"),PA=(0,C.h)("merged-agent-skills");class IA{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,i.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(xA("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 PA.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}}},[a,c]=await Promise.all([Promise.all(n),o()]),l=a.flat(),u=this.getPromptSortContext?.(),d=Wm(l,u??jm);let h=d;return c.ok?c.paths.length>0&&(h=d.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,c.paths)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(RA));var t})),void 0!==u?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:CA(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(h,u):h}catch(e){t.error=e,t.hasError=!0}finally{EA(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()}),IA.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()}}IA.CHANGE_COALESCE_MS=1500;const RA=`/${mm.configDir}/${mm.subdir}/`,TA=(0,C.h)("skill-sync-manifest"),AA=".sync-manifest.json";async function $A(e,t){try{const r=await(0,Ys.readFile)((0,s.join)(e,AA),"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:(TA.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===el(r)||TA.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function MA(e,t,r){e.skills[t]={lastSyncedAt:r}}function DA(e,t){delete e.skills[t]}var OA=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 FA=(0,C.h)("builtin-skills-sync");function NA(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jA(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 LA(e){const t=qp(e.content),r=NA(t.data)?t.data:{};return zp(`${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={...NA(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 UA(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 BA(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,Ys.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,Ys.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Ys.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,Ys.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Ys.writeFile)(t,r,"utf-8")}try{await(0,Ys.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==el(e))throw e}try{await(0,Ys.rename)(n,r)}catch(e){throw i&&(await(0,Ys.rename)(o,r),i=!1),e}i&&(await(0,Ys.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Ys.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Ys.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===el(t)||FA.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Ys.mkdir)(n,{recursive:!0}),await(0,Ys.writeFile)(o,i,"utf-8"),!0}async function BA(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Ys.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===el(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await BA(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function WA(e,t){try{return(await(0,Ys.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===el(r)||FA.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function HA(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const a=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,i.VI)(e.withName("syncBuiltinSkills")),!1).ctx,c=Date.now(),l=t.skillDir??bm((0,o.homedir)()).dirPath;await(0,Ys.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([$A(l,a),WA(a,l)]),h=u.lastInventoryAt;(void 0===h||c-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([qA((0,s.join)(r,"SKILL.md")),"canvas"===e?qA((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}})));FA.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){FA.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(a,l,d,u),u.lastInventoryAt=c);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):FA.warn(a,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:(t.canvasKit,km((0,o.homedir)()).dirPath),m=void 0!==f&&await qA((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?c-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,i=void 0!==t&&Ud(t,"local"),d=void 0!==t&&!i,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&i)jA(t),f!==l&&await(0,Ys.mkdir)(f,{recursive:!0}),await UA(a,f,{id:e,fileContent:LA(t),resources:t.resources??{}})?v++:b++,MA(u,e,c);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Ys.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),DA(u,e),h&&(S.push(e),FA.info(a,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?c-r.lastSyncedAt:null}))}else r||MA(u,e,c)}catch(t){FA.warn(a,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),n=(0,s.join)(e,AA);await(0,Ys.mkdir)(e,{recursive:!0}),await(0,Ys.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,Ys.rename)(r,n)}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===el(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?FA.warn(a,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):FA.debug(a,"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{OA(r)}var n}async function qA(e){try{return await(0,Ys.stat)(e),!0}catch(e){const t=el(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const zA=(0,C.h)("managed-skills-sync");function GA(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 VA{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(...rh(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=GA(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var KA=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 JA(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class ZA{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??Au,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: ${tl(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: ${tl(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(Gf));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Gf(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=JA(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 qf({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${tl(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,Ys.realpath)(r);if(!(await(0,Ys.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,Ys.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 Uf(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}: ${tl(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,ye.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,i.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(),a=JA(this.marketplaceOptions,this.userHomeDirectory),c=o.importThirdPartyPlugins,l=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??a.length>0;if(!c&&!u&&!l)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 d=(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??Au,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(Hf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>qf({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Au,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,Ys.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,Ys.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,Ys.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{op(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Ys.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 Uf(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,Ys.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=zf(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=>zf(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:c,loadUserLocal:l,loadCursorFirstParty:u&&a.length>0,marketplaceSources:a.length>0?a.map((e=>({...e,onCursorError:d}))):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: ${tl(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{KA(e)}}}var XA=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function QA(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function YA({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||FE(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class e${constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new XA.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new XA.aYW({}))}}function t$(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 r${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 n${constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new r$((()=>this.fetchSettings())),this.hostMcpBridgeClients=new WeakSet,this.teamRepos=new r$((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new r$((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){const e=this.settingsGeneration;try{const t=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e>=this.lastFetchedGeneration&&(this.lastFetchedSettings=t,this.lastFetchedGeneration=e),t}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){return this.settings.get().catch((()=>{}))}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(n){if(function(e,t){return!my(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,hy.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=YA({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?YA({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}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,hy._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=QA(t.url);return void 0!==n&&r.some((e=>QA(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}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=LE({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===XA.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===XA.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===XA._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===XA.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:t$(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 o$=new ry,s$={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Vc((0,ye.q6)(),o$,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?Qs(r):void 0),workspaceRoots:n,createdAt:new Date}}},i$=(0,C.h)("ControlledConversationActionManager");class a${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,P.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 qr.QFf({action:{case:"cancelAction",value:new qr.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 P.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 P.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 P.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 P.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,P.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new qr.QFf({action:{case:"userMessageAction",value:new qr.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){i$.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof P.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 P.W2("ControlledConversationActionManager disposed")))}}var c$=r("../cursor-sdk-local-runtime/dist/utils/logger.js");const l$="x-blob-encryption-key";function u$(e,t){const r={...t};return void 0!==r[l$]||(0,Tn.TU)(e)&&(r[l$]=e),r}const d$=new Map;function h$(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function p$(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 f$(e){return new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:e})})}})}function m$(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function g$(e){e?.catch((e=>{c$.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const w$=new Set(["mcp.slack.com","setup.shopify.com"]);async function y$(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!==(i=e,a=r.restMcpHost,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?Wv(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!w$.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await _b(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===Sb(t.CLIENT_ID)?{...c,...t,CLIENT_ID:c.CLIENT_ID}:{...c,...t}:c:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}class v${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 y$(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class b${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 S${constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class k${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 vy(t,n.configPath??"another config")}return await o(e,r)}}class _${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={};for(let e=0;e({prefix:t,scope:r,fileSource:new P_(e,"enterprise"===r||"env"===r?sv:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new b$(t,l),p=new S$(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,iv.indexOf(t)0?[new k$(f)]:[]],g=new I_(u?new v$(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new _$(y)}static init(e,t,r,n=!1,o,i={}){const a=new N_(s.join(r,"mcp-auth.json"));(async function(e){await(0,Ys.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new ky(s.join(r,"mcp-approvals.json"),t);return new C$(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 E$="cursor-plugins/local";function x$(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===E$)return r}class P$ extends u_{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class I${constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Ys.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,Ys.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Ys.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class R${constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return c$.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&D$(r))continue;const e=M_(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}}):c$.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 T${constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:M$(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function A$(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};return{async createLease(a){const c=a.workspaceState,l=c.projectRoot??c.workingDirectory,u=c.projectDirectory;if(!l||!u)return new l_;const d=new I$((0,s.join)(u,"mcp-disabled.json")),h=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return C$.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new N_((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new ky((0,s.join)(n,"mcp-approvals.json"),r),p=[new Ey,new Sy(h),new A_(t),new by(a)],f=[];return c&&f.push({prefix:"",loader:new $_((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new $_((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),$$(f)}({teamSettingsService:t,projectRoot:l,projectDirectory:u,ignoreApprovals:r,disabledStore:d,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),p=[],f=e.inlineMcpServers??{};if(Object.keys(f).length>0){const e=new N_((0,s.join)(u,"mcp-auth.json")),r=[new Ey,new A_(t)];p.push({prefix:"",loader:new I_(new T$(f),e,r,i)})}const m=x$(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new ky((0,s.join)(u,"mcp-approvals.json"),l),o=new N_((0,s.join)(u,"mcp-auth.json")),a=[new Ey];r||a.push(new Sy(e)),a.push(new A_(t),new by(d));const c=new VA(m.pluginsService),h=new I_(new R$(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new l_;const g=$$(p),w=await g.load(e.initializationCtx??(0,ye.q6)(),e.cache);return new P$(w)}}}function $$(e){return 1===e.length?e[0].loader:new _$(e)}function M$(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 D$(e){return"claude-plugin"===e.pluginSource}function O$(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function F$(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class N${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>N$.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===Tr.symbol||e===ge.symbol?{kind:"path"}:e===Ir.symbol||e===Rr.symbol||e===le.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=F$(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===Rr.symbol&&O$(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new xr.FI({event:{case:"hookContext",value:new xr.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===Tr.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=F$(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 j$(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}N$.CARRIERS_BY_EXEC_ID_MAX=32,Error,bl.execFileSync,new Map,ti.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 L$=["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(j$);function U$(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(B$,"\n\n"):r).trim()}(e,L$)}["system_reminder","system-reminder"].map(j$);const B$=/\n{3,}/g;function W$(e){const t=(0,Zs.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,Zs.sh)(e.parentConversationId);return`${Zs.O2}/${r}/subagents/${t}.${e.ext}`}return`${Zs.O2}/${t}/${t}.${e.ext}`}function H$(e){const t=(0,Zs.sh)(e.conversationId);return`${Zs.O2}/${t}.${e.ext}`}function q$(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(W$({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(W$({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(H$({conversationId:e.conversationId,ext:n}));return n}var z$;(()=>{const e=globalThis.Intl?.Segmenter;e&&new e(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(z$||(z$={}));var G$=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},V$=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 K$(e){switch(e){case qr.xyI.AGENT:return"agent";case qr.xyI.ASK:return"ask";case qr.xyI.PLAN:return"plan";case qr.xyI.DEBUG:return"debug";case qr.xyI.TRIAGE:return"triage";case qr.xyI.MULTITASK:return"multitask";case qr.xyI.CUSTOM:return"custom";case qr.xyI.UNSPECIFIED:default:return"agent"}}function J$(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 Z$(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 X$=new TextEncoder,Q$=new TextDecoder,Y$=new class{serialize(e){const t=JSON.stringify(e,J$);return X$.encode(t)}deserialize(e){const t=Q$.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Z$):JSON.parse(t)}};function eM(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function tM(e){return"system"!==e.role&&!eM(e)}function rM(e,t){return"user"===e.role&&"user"===t.role}async function nM(e,t,r){const n=await t.getBlob(e,r);return n?qr.Anz.fromBinary(n).summarizedMessages:[]}async function oM(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=Y$.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 sM(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 oM(e,t,o,n);r&&n.messages.push(r)}return n}async function iM(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=oM(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 cM(e){return U$(e)}const lM=/[\s\S]*?<\/think>/gi,uM=/[\s\S]*?<\/thinking>/gi,dM=/\n{3,}/g;function hM(e){let t=e;return t.includes("<")&&(t=t.replace(lM,"").replace(uM,"")),(t.includes("\n\n\n")?t.replace(dM,"\n\n"):t).trim()}function pM(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?cM(e):e;return r?hM(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=hM(t?cM(e.text):e.text);return aM({...e,text:r},!1)}return aM(e,t)})).filter(Boolean).join("\n")}function fM(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?cM(n):n,s="assistant"===e.role?hM(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?cM(r.text):r.text,s="assistant"===e.role?hM(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 mM(e){return e.endsWith("\n")?e:`${e}\n`}function gM(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 wM(e){if("system"===e.role||eM(e))return;const t=fM(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 yM{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=W$({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=G$(o,(0,i.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=gM(n),{appendFile:a,streamFullJsonlWrites:c,writeJsonl:l,writeText:u,writeJson:d}=this.options;if(a&&c&&l&&!u&&!d&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:a,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const h=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=G$(n,(0,i.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const a=(0,i.OA)(o.ctx),c=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await nM(a,t,e);return s+=r.length,await sM(a,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of g)c.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=G$(n,(0,i.VI)(e.withName("hydratePromptMessages")),!1),y=await sM(a,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const v=y.messages.filter(tM);return c.push(...v),c}catch(e){n.error=e,n.hasError=!0}finally{V$(n)}}(s.ctx,this.blobStore,t);if(0===h.length&&0===o.jsonlLines.length)return!0;let p;if((this.options.writeText||e)&&(p=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=pM(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(h)),this.options.writeText){const e=p??"",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=fM(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(h);if(e||o.jsonlLines.length>0){const n={mode:K$(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&&rM(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=wM(e);t&&r.push(t)}return r.join("\n")}(h);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&p?.trim())try{const t=(await e(p)).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"),mM(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{V$(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,a=0,c=0;const l=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===a?await this.writeFile(r,e):await n(r,e),a++,c+=e.length},u=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await l())};let d,h=0;const p=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 nM(e,t,s)}catch{continue}await iM(e,t,r,o,{skipFailedReads:!0,visit:n})}return await iM(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{tM(e)&&await n(e)}}),o}((0,i.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(h++,1!==h?(2===h&&d&&(rM(d,e)||await u(wM(d)),d=void 0),await u(wM(e))):d=e)}));d&&await u(wM(d));for(const e of t.terminalLines)await u(e);await l(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",a),e.span.setAttribute("writtenChars",c),e.span.setAttribute("hydratedBlobCount",p.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",p.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",p.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",p.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",p.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",p.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",p.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const a=t.rootPromptMessagesJson.length,c=gM(o),l=c.jsonlLines.length>0;if(a===n&&!l&&!o.overviewFactory)return a;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&a>=n&&(a>n||l))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?a:0;const d=G$(s,(0,i.VI)(e.withName("writeFromStateIncremental")),!1);if(a===n&&l)try{return await u(this.resolveFilePath(r,"jsonl"),mM(c.jsonlLines.join("\n"))),a}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)?a:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await sM(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=wM(e);t&&s.push(t)}if(s.push(...c.jsonlLines),s.length>0){const e=mM(s.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}return a}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)?a:0:0}}catch(e){s.error=e,s.hasError=!0}finally{V$(s)}}}function vM(e){return Object.values(ke).some((t=>t===e))}function bM(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 SM(e){return Ve(e)?`prompt:${e.prompt}`:`command:${e.command}`}function kM(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class _M{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(SM(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=SM(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(!Ae(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ae(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in _e&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ae(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=Ne(r,this.logger),o=St(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=St(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,...kM(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))vM(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))vM(e)&&t.add(e);return t}}const CM="Read",EM="Write",xM="Delete",PM="List",IM="Grep",RM="Shell",TM="ReadLints";function AM(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const $M=new Set([CM,EM,xM,PM,IM,TM]);function MM(e){const t=AM(e,"tool_name"),r=[AM(e,"file_path"),"string"==typeof t&&$M.has(t)?AM(AM(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const DM=(0,C.h)("cli-hooks-executor");function OM(e){try{return(0,ti.statSync)(e).isFile()}catch{return!1}}const FM="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function NM(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function jM(e,t){const r=NM(e,t);if("string"==typeof r||null===r)return r}class LM{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,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,oh.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,Zs.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=q$(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,Ys.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,Zs.Rv)((0,o.homedir)(),this.workspacePath),n=q$({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Ys.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,...kM(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?We(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?We(n,t):n).some((e=>Ke(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=NM(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 Qe.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===ke.subagentStop){const e=jM(t,"subagent_id"),r=jM(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:[this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===ke.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return Be(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=Be(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 Be(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return Be(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=We(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)Ve(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):Ke(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,bi.o1)(t,r),[o,i,a]=await Promise.all([(0,bi.DN)(n),(0,bi.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,bi.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:MM(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===ke.stop||e===ke.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 We(n,u))Ke(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=je(`Hook execution failed: ${n}`),r=ot(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return DM.warn((0,ye.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;if(1===t.length)return t[0];const r=Xe.includes(e),n=e===ke.sessionStart,o=e===ke.workspaceOpen,s=Ge.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=Ye(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?et(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=Ye(i[e],l)}var a,c;return i}(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=ot(e,je(`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=ot(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=ot(e,je(`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=ot(e,je(`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=st(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=st(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=rt({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+FM}),{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+FM}),{success:!1,source:s,index:i})}const y=Ze(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=rt({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,ye.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 tt(e)?nt(0,{permission:"allow"}):e===ke.beforeSubmitPrompt||e===ke.sessionStart?nt(0,{continue:!0}):e===ke.stop?nt(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=ot(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=ot(e,je(`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=wt.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:OM}):t.command;let w;if(m)w=e?yt(g):g;else if("windows_temp_file"===f){d=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Ys.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 | ${yt(t)} }`+gt(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+gt(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=jM(n,"conversation_id")??void 0,v=jM(n,"session_id")??void 0,b=jM(n,"transcript_path"),S=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),k=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:S?.at(-1)??y:v,_=this.buildHookEnvironment({transcriptPath:b,sessionId:k,conversationId:y,executionEnv:i}),C={};for(const[e,t]of Object.entries(_))void 0!==t&&(C[e]=t);void 0!==a&&(C.CURSOR_PLUGIN_ROOT=a,C.CLAUDE_PLUGIN_ROOT=a);const E=(0,ye.q6)(),x=new xc.StringDecoder("utf8"),P=new xc.StringDecoder("utf8");let I,R="",T="",A=null,$=!1;for await(const e of this.shellExecutor.execute(E,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:C,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),$=!0);break;case"stdout":R+=x.write(e.data);break;case"stderr":T+=P.write(e.data);break;case"exit":A=e.code,I=e.aborted}if(R+=x.end(),T+=P.end(),m&&!$)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const M=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:R,stderr:T,exitCode:A,duration:M}}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,Ys.rm)(d,{recursive:!0,force:!0})}catch{}}}}class UM{constructor(e){this.config=e,this.configuredSteps=_M.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var BM=r("node:perf_hooks");function WM(e,t){void 0!==e&&t.length>0&&e.push(...t)}class HM 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 qM=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function zM({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 HM({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new qM.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ge).map((e=>{if(!function(e){return e===ke.sessionStart||e===ke.beforeSubmitPrompt||e===ke.preToolUse||e===ke.postToolUse||e===ke.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}]})));class GM extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class VM extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const KM="To view or modify configured hooks, go to Cursor Settings > Hooks.";function JM(e,t){return Ue(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${KM}`)}function ZM(e){return function(e){return e instanceof GM}(e)||function(e){return e instanceof VM}(e)}const XM=(0,C.h)("generic-hooks");function QM(e,t,r,n){try{return zM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof HM)return XM.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const YM=e=>Math.round(1e3*e)/1e3;function eD(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,Js.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 wl(e.signal,(()=>t.executeHookForStep(ke.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));WM(i,QM(e,r,ke.postToolUseFailure,h?.additional_context))}catch(t){XM.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await wl(e.signal,(()=>t.executeHookForStep(ke.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));WM(i,QM(e,r,ke.postToolUse,u?.additional_context))}catch(t){XM.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 tD(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await wl(e.signal,(()=>r.executeHookForStep(ke.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=Ue(r);try{WM(n.hookContextCollector,zM({hookEventName:ke.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof HM))throw t;XM.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))),WM(n.hookContextCollector,zM({hookEventName:ke.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(ke.preToolUse,s.toolName)??!1,c=n instanceof HM;if(a){const e=je(`${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}}XM.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(ZM(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 rD(e){return e.toolCallId}function nD(e,t,r,n){return{async execute(o,s,i){const a=sD(o,t),{hookContext:c,helpers:l}=eD(o,s,a,r,n,i);let u;try{u=await tD(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=BM.performance.now();try{const t=await e.execute(o,s,i),r=YM(BM.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(ZM(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);XM.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=YM(BM.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*oD(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function sD(e,t){const r=Et(e),n=e.get(_t);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===ke.preToolUse||e===ke.postToolUse||e===ke.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 iD(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class aD{async readFile(e){try{return await Ys.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Ys.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,Ys.lstat)(e)).isSymbolicLink())return!0}catch(e){if(iD(e))return!0;throw e}return!1}(e,t)}}class cD{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 Nr.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 Nr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Nr._G({result:{case:"success",value:new Nr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function lD(e){return!!e&&e.type!==Bi.vc.INSECURE_NONE&&e.type!==Bi.vc.UNSPECIFIED}async function uD({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(ke.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=JM("Command execution",i.user_message);throw new GM(e)}if("ask"===i?.permission)return a=i.user_message,new xr.In({kind:xr.b.FORCE_PROMPT,reason:a});var a}const dD={toolName:RM,getToolCallId:rD,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 Cr.Lt({result:{case:"rejected",value:new xr.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=lD(r.sandboxPolicy);xt(t,ke.beforeShellExecution)&&Ur(r,await uD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class hD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,dD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const pD={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Cr.nt({result:{case:"error",value:new Cr.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 fD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,pD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const mD={toolName:"ComputerUse",getToolCallId:rD,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ag.ks({result:{case:"error",value:new Ag.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 gD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,mD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const wD={toolName:xM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Er.Pi({result:{case:"rejected",value:new Er.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 yD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,wD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const vD={toolName:TM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new UI.Ek({result:{case:"rejected",value:new UI.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 bD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,vD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const SD={toolName:"Fetch",getToolCallId:rD,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Nw.uN({result:{case:"error",value:new Nw.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 kD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,SD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _D={toolName:IM,getToolCallId:rD,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 oy.Ud({result:{case:"error",value:new oy.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 CD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,_D)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ED={toolName:PM,getToolCallId:rD,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 bI.fv({result:{case:"rejected",value:new bI.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 xD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,ED)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PD=(0,C.h)("hooks-exec:mcp");function ID(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(ID):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&ID(e))))}function RD(e,t,r,n){try{return zM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof HM)return PD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class TD{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(ke.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(ke.beforeMCPExecution)))return new er.iz({result:{case:"error",value:new er.Nh({error:`"${dr}" 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=sD(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,Js.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(ke.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{WM(i,zM({hookEventName:ke.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof HM))throw t;PD.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 er.iz({result:{case:"permissionDenied",value:new er.HQ({error:JM("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(!ID(n))throw new TypeError("updated_input value is not JSON");t.args[e]=sr.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){PD.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}WM(i,zM({hookEventName:ke.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(ke.preToolUse,c)??!1,l=t instanceof HM;if(r){const r=je(`${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 er.iz({result:{case:"permissionDenied",value:new er.HQ({error:JM("MCP tool execution",r),isReadonly:!1})}})}PD.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=xt(e,ke.beforeMCPExecution)?await n.executeHookForStep(ke.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=JM("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:t,isReadonly:!1})}})}const g=BM.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=YM(BM.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){PD.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(ke.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 er._Z({content:{case:"text",value:new er.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 er._Z({content:{case:"text",value:new er.zN({text:String(e.text)})}})):t.push(new er._Z({content:{case:"text",value:new er.zN({text:JSON.stringify(e)})}}))}else t.push(new er._Z({content:{case:"text",value:new er.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new er.iz({result:{case:"success",value:new er.QW({content:t,isError:r})}})}catch(t){return PD.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=YM(BM.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(ke.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return WM(c,RD(e,n,ke.postToolUse,l?.additional_context)),l}catch(t){return void PD.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(ke.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});WM(u,RD(e,n,ke.postToolUseFailure,d?.additional_context))}catch(t){PD.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const AD={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new er.kP({result:{case:"error",value:new er.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 $D{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,AD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const MD={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 er.ZD({result:{case:"error",value:new er.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 DD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,MD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OD={toolName:CM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new tr.sV({result:{case:"rejected",value:new tr.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?.(ke.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${KM}`}(t,e instanceof Error?e.message:String(e));throw new VM(r,e)}}((()=>o.executeHookForStep(ke.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=JM("File read",a.user_message);throw new GM(e)}}};class FD{constructor(e,t,r){this.wrappedExecutor=new cr(nD(e,t,r,OD))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ND={toolName:"RecordScreen",getToolCallId:rD,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new MR.Tj({result:{case:"failure",value:new MR.yH({error:t})}}),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 jD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,ND)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function LD(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const UD={toolName:RM,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 xr.W4({result:{case:"rejected",value:new xr.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:LD(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||"";xt(t,ke.beforeShellExecution)&&Ur(r,await uD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:lD(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=LD(r);await o.executeHookForStep(ke.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:lD(t.requestedSandboxPolicy),tool_use_id:i})}};class BD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,UD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class WD{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 HD={toolName:RM,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 xr.FI({event:{case:"rejected",value:new xr.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new xr.FI({event:{case:"hookContext",value:new xr.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new WD,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=lD(r.requestedSandboxPolicy);xt(t,ke.beforeShellExecution)&&Ur(r,await uD({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=lD(t.requestedSandboxPolicy);await n.executeHookForStep(ke.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class qD{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=sD(o,t),{hookContext:c,helpers:l}=eD(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await tD(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of oD(n,c))yield e;return}const h=BM.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=YM(BM.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of oD(n,c))yield e;throw e}const f=YM(BM.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){XM.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 oD(n,c))yield e}}}(e,t,r,HD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class zD{constructor(e,t,r){const n=new Map;this.wrappedExecutor=nD(e,t,r,function(e){return{toolName:EM,getToolCallId:rD,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 Pr.v3({result:{case:"error",value:new Pr.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?.(ke.afterFileEdit))return;let s,i=!1;try{(await(0,Ys.stat)(r.path)).size>262144?i=!0:s=await sc(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?.(ke.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,ax.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(ke.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await sc(e),r=ma(t),o=Buffer.byteLength(t,"utf8");return new Pr.v3({result:{case:"success",value:new Pr.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 GD(e,t,r){return t===e.symbol}function VD(e,t,r){return GD(Ir,e)?new BD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Rr,e)?new qD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Tr,e)?new zD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Gt,e)?new TD(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):GD(lr,e)||GD(ur,e)?new FD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Dt,e)?new xD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Se,e)?new CD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ve,e)?new kD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ge,e)?new yD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(we,e)?new bD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Vt,e)?new $D(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Kt,e)?new DD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(le,e)?new hD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ue,e)?new fD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(me,e)?new gD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Or,e)?new jD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Fr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new cD(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class KD{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===Pt.symbol)return new $t(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=VD(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=VD(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=Pt;yield[e,new $t(this.hookExecutor)]}}const JD={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ZD(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>ZD(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,ri.oG)(),args:[...dt,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,bl.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}}}function XD(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function QD(e){return"string"==typeof e&&e.length>0?e:void 0}function YD(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function eO(e){if(Array.isArray(e)&&e.every(YD))return e.map((e=>({id:e.id,value:e.value})))}class tO{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 rO(e,t={}){const r=await new _M(new aD,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?bM():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 UM(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...JD,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new LM(r,i,a,(t.createTerminalExecutor??ZD)(),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 nO(e={}){return{createHooksRuntime:t=>rO(t.workspaceState,e)}}var oO=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function sO(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function iO(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 ry,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,Dn.createClient)(oO.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await HA(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return zA.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,ye.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new XA.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:pO(),getAgentSkills:async e=>[]};const p=(0,ye.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=aO(t);return{getAllCursorRules:async t=>cO(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?pO():1===m.length?m[0]:new mg(m,(()=>jm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=aO(t);return{getAllCursorRules:async t=>cO(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>cO(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new wg(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 Pg(e,t))):[],v=0===y.length?new Sg:1===y.length?y[0]:new Rg(y),b=x$(o.services.pluginBootstrapOutputs),S=b&&a?new vg(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new Tg((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,_=new mg([g,w,...S?[S]:[]],(()=>jm)),C=new IA([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),E=new Rg([v,...k?[k]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:S,pluginSubagentsService:k,mergedCursorRulesService:_,mergedAgentSkillsService:C,mergedSubagentsService:E};const x={cursorRulesService:_,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:E};return x},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 sO(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function aO(e){const t=Promise.all(e.allowedRoots.map(dO)),r=Promise.all(e.excludedRoots.map(dO));return async e=>{const[n,o,s]=await Promise.all([hO(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>lO(n,e)))&&o.some((e=>lO(n,e)))}}async function cO(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function lO(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function uO(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function dO(e){try{return uO(await(0,Ys.realpath)(e))}catch{return uO(e)}}async function hO(e){try{return uO(await(0,Ys.realpath)(e))}catch{return}}function pO(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function fO(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":c$.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":c$.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){c$.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=mO(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 am(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,Dn.createClient)(oO.I,e.dashboardTransport),n=Up((async()=>{try{return await r.getEffectiveUserPlugins(new XA.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Up((async()=>{if(void 0===o)return{plugins:[]};try{const e=await am(o);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||rm(t)})).map((({key:e,entry:t})=>{const r=cm(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 i=[];if(n.length>0)try{const e=n.map((e=>{const t=cm(e.key);return new XA.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new XA.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new dh(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new dh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=mO(d),p=new ZA(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:E$,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)c$.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)c$.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 mO(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class gO{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const wO=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function yO(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 vO(e){const t=yO(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function bO(e){const t=yO(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 SO(e){const t=vO(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>vO(t.host).length-vO(e.host).length));for(const e of r){const r=vO(e.host);if(t===r)return bO({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return bO({reportedWorkspacePath:e.reported,suffix:n})}}}const kO={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class _O extends bA{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await sO(this.sessionMcpLease)}}}function CO(e){const t=new ry;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 gO,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new l_,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 l_:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Fw(u,d):new Ow(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 kO;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return kO}}(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),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 bA(u):new _O(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Fr);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(Fr,{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=>SO({value:e,roots:o})??e));for(const e of wO){const t=n[e];if(void 0===t||""===t)continue;const r=SO({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??yO(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 sO(c),e}}}}const EO=["cursorRulesService","getAgentSkills","subagentsService"],xO=new WeakSet;function PO(e){("object"==typeof e&&null!==e||"function"==typeof e)&&xO.add(e)}function IO(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&xO.has(e)}function RO(e,t){const r=Object.keys(t).filter((e=>!EO.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${EO.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of EO)Object.hasOwn(t,r)&&(e[r]=t[r])}async function TO(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&&(PO(s.cursorRulesService),PO(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&RO(n,e)}return n}catch(t){try{await AO(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 AO(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await sO(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||IO(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||IO(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 sO(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 $O=["project","user","team","mdm","plugins"],MO=new Set([...$O,"all"]);function DO(e){if(void 0===e||0===e.length)return FO([]);for(const t of e)if(!MO.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{...FO($O),all:!0}}return FO(e.filter((e=>"all"!==e)))}function OO(e,t){return e[t]}function FO(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 NO=Object.freeze({}),jO=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:NO});async function LO(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 sO(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function UO(e={}){const t=function(e={}){return{workspace:e.workspace??s$,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({...jO.metadata,...e.metadata}),r={...jO,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await TO(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,Mn.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 LO(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 LO(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 TO(t,r,n);s?await AO(i,{disposeLocalExtensibility:l}):(o=i,await AO(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await AO(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class BO{async requestApproval(e){return{approved:!0}}}class WO{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 HO{async open(e,t){}async getDiagnostics(e,t){return[]}}class qO{async getCodebaseReference(e,t){}}class zO{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class GO{constructor(e){this.subagents=e.map((e=>new gn.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:gn.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}let VO;function KO(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Qs(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,Zs.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,ti.statSync)(e).isDirectory()&&((0,ti.accessSync)(e,ti.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,Zs.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,Zs.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===VO&&(VO=function(e){return(0,ti.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),VO)})}async function JO(e,t){const r=(0,s.dirname)(e);await(0,Ys.mkdir)(r,{recursive:!0}),await(0,Ys.writeFile)(e,t,"utf-8")}class ZO{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=KO(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=W$({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new yM(this.projectDir,e.blobStore,JO,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new yM(this.projectDir,e.blobStore,JO,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=W$({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){c$.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,Tn.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=W$({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=W$({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(KO(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const XO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,QO="User aborted/interrupted manually.";class YO{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.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,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 Sn}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(!XO.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&kn(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,Mn.C)(),o=function(e){const t=new Tn.We,r=(0,Tn.sh)(e),n=new Tn.pH(new Tn.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 ZO({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:gn.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:gn.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 mn.a3({status:mn.jh.ACCEPTED}):new mn.a3({status:mn.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){c$.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 mn.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,Mn.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}async executeSubagentOnce(e,t,r,n){let o,s=0;const i=new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:r.prompt})})}}),a=new qr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new a$,l={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&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return en(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return rn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return sn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new $o.tz({result:{case:"rejected",value:new $o.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return nn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},u={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const d=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==d&&""!==d?d:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new re(f,function(e){const t=[Y(Tr,$r(e.errorMessage)),Y(ge,Mr(e.errorMessage)),Y(Gt,Dr(e.errorMessage))];return e.wrapShell&&t.push(Y(Ir,function(e){return{execute:async(t,r)=>new xr.W4({result:{case:"permissionDenied",value:Ar(e,r)}})}}(e.errorMessage)),Y(Rr,function(e){return{async*execute(t,r){yield new xr.FI({event:{case:"permissionDenied",value:Ar(e,r)}})}}}(e.errorMessage)),Y(le,function(e){return{execute:async(t,r)=>new Cr.Lt({result:{case:"permissionDenied",value:Ar(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(Y(ue,function(e){return{execute:async(t,r)=>new Cr.nt({result:{case:"error",value:new Cr.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})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),i,a,l,m,n.agentStore.getBlobStore(),c,u,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:u$(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:QO}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return c$.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:QO}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:QO}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!kn(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 mn.zJ({result:{case:"stillRunning",value:new mn.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 mn.zJ({result:{case:"complete",value:new mn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new mn.zJ({result:{case:"error",value:new mn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new mn.zJ({result:{case:"stillRunning",value:new mn.L5({agentId:r})}}):new mn.zJ({result:{case:"notFound",value:new mn.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 mn.zJ({result:{case:"stillRunning",value:new mn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new mn.zJ({result:{case:"complete",value:new mn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new mn.zJ({result:{case:"error",value:new mn.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 eF=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),tF=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),rF=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),nF=r("./src/agent/analytics.ts"),oF=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const sF={[Ag.w3.UNSPECIFIED]:"unspecified",[Ag.w3.LEFT]:"left",[Ag.w3.RIGHT]:"right",[Ag.w3.MIDDLE]:"middle",[Ag.w3.BACK]:"back",[Ag.w3.FORWARD]:"forward"},iF={[Ag.Dh.UNSPECIFIED]:"unspecified",[Ag.Dh.UP]:"up",[Ag.Dh.DOWN]:"down",[Ag.Dh.LEFT]:"left",[Ag.Dh.RIGHT]:"right"},aF={[Ag.EB.UNSPECIFIED]:"unspecified",[Ag.EB.TAP]:"tap",[Ag.EB.DOWN]:"down",[Ag.EB.UP]:"up"};function cF(e){return sF[e]??"unspecified"}function lF(e){return void 0===e?void 0:{x:e.x,y:e.y}}function uF({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:lF(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 dF(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 hF("tool-call-started",e.message.value);case"partialToolCall":return hF("partial-tool-call",e.message.value);case"toolCallCompleted":return hF("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"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=dF(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"modelCallCompleted":case void 0:return null;default:return e.message,null}}function hF(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:yF(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:vF(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:bF(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:SF(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:_F(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:CF(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:EF(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:PF(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:IF(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:TF(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:AF(t.mode)},...r?{result:$F(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:RF(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:MF(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:OF(e.status)})))},...r?{result:DF(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:lF(e.value.coordinate)};case"click":return{type:"click",coordinate:lF(e.value.coordinate),button:cF(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:cF(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:cF(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:lF(e.value.coordinate),direction:iF[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:aF[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?uF(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:pF(t),...r?{result:gF(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"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":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 pF(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:fF(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:mF(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function fF(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function mF(e){switch(e){case gn.FL.AGENT:return"agent";case gn.FL.PLAN:return"plan";default:return"unspecified"}}function gF(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:wF(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function wF(e){switch(e){case gn.qL.AGENT_REQUEST:return"agentRequest";case gn.qL.USER_REQUEST:return"userRequest";case gn.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function yF(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 vF(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 bF(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 SF(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]=kF(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:kF(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function kF(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 _F(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 CF(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 EF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:xF(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function xF(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(xF)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function PF(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:FF(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 IF(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 RF(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 TF(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 AF(e){switch(e){case MR.$u.START_RECORDING:return"START_RECORDING";case MR.$u.SAVE_RECORDING:return"SAVE_RECORDING";case MR.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function $F(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 MF(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 DF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:OF(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function OF(e){switch(e){case oF.Vj.UNSPECIFIED:case oF.Vj.PENDING:return"pending";case oF.Vj.IN_PROGRESS:return"inProgress";case oF.Vj.COMPLETED:return"completed";case oF.Vj.CANCELLED:return"cancelled";default:return"pending"}}function FF(e){switch(e){case UI.h_.UNSPECIFIED:case UI.h_.ERROR:return"error";case UI.h_.WARNING:return"warning";case UI.h_.INFORMATION:return"information";case UI.h_.HINT:return"hint";default:return"error"}}const NF={type:"object",properties:{},additionalProperties:!0};function jF(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function LF(e){return"text"===e.type?new er._Z({content:{case:"text",value:new er.zN({text:e.text})}}):new er._Z({content:{case:"image",value:new er.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function UF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var BF=r("./src/agent/errors.ts");const WF="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 HF(e){return{async execute(){throw new Error(e)}}}function qF(e){var t;e.register(Ir,HF(WF)),e.register(Rr,(t=WF,{async*execute(){throw new Error(t)}})),e.register(le,HF(WF)),e.register(Lr,HF(WF)),e.register(ue,HF(WF)),e.register(_r,HF(WF)),e.register(we,HF("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(be,HF("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var zF=r("./src/agent/filesystem/executors.ts"),GF=r("./src/agent/filesystem/compose.ts"),VF=r("./src/agent/filesystem/trees.ts"),KF=r("./src/agent/filesystem/walk.ts");const JF="/tmp",ZF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function XF(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,KF.eI)(e.hostProjectDir),r=(0,KF.eI)(e.writePath);return"/"!==t&&(0,KF.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,KF.eI)(e.writePath):(0,KF.eI)(`${JF}/${r}`);if(!(0,KF.hJ)({path:n,prefix:JF}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(JF,pl);return s.default.posix.dirname(n)===i&&ZF.test(o)?s.default.posix.join(JF,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 QF{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,KF.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([YF(e,s.posix.join(t,".cursor/rules")),eN(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 YF(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 tN(e,t),n=void 0===r?null:b(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 eN(e,t){const r=await tN(e,t);if(void 0!==r)return fg({path:t,body:y({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function tN(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const rN={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},nN={async exec(){throw new Error("git is not available in a FileSystem session")}},oN={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function sN(e){return{cursorRulesService:!0===e.includeProjectRules?new QF(e.fs,e.workspace):rN,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:nN,ignoreService:oN,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function iN(e,t){const r=t.workspace??"/",n=(0,zF.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:XF({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...sN({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:JF,excludeHooks:!0,excludeProjectMcp:!0}}var aN=r("./src/agent/executor-common.ts"),cN=r("./src/agent/native/vendored-tree-sitter.ts"),lN=r("./src/agent/platform-package-locator.ts"),uN=r("./src/agent/sdk-config.ts"),dN=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hN=r("./src/agent/utils/logger.ts");const pN={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fN=new Map;async function mN(e){try{const t=await async function(e){const t=await(0,aN.dC)(e,aN.EV);if(!t)return;const r=aN.EV.endsWith("/")?aN.EV.slice(0,-1):aN.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,aN.tF)(),"x-ghost-mode":(0,aN.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hN.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gN(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pN;const r=new dN.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gN(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,aN.tF)()}}}catch(e){hN.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,aN.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 hN.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pN}}function gN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wN(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yN=r("./src/agent/tools-option.ts");class vN{async requestApproval(){return{approved:!0}}}function bN(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof bA))throw new BF.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Gt),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Nt}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new er.iz({result:{case:"error",value:new er.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:UF(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?sr.Struct.fromJson(t.structuredContent):void 0;return new er.iz({result:{case:"success",value:new er.QW({content:t.content.map(LF),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 er.iz({result:{case:"error",value:new er.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vN;e.resources.base.register(Gt,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Nt}(t)){const o=await lE(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 SN=new Set(["127.0.0.1","localhost","[::1]"]);function kN(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _N(){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 CN={warn(){},error(){}},EN={log(){}};class xN{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PN(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 PN(e){switch(e.type){case $w.Shell:return"this shell command";case $w.Mcp:return"this MCP tool call";case $w.Write:return"this file edit";case $w.Delete:return"this file deletion";default:return"this operation"}}function IN(e){return void 0!==e&&"insecure_none"!==e.type}async function RN(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,ye.q6)().with(C._O,EN),c=DO(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&&SN.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}`);jc=e}((0,uN.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(aN.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let d=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,aN.ly)(r.apiKey),(0,aN.mU)(r.apiKey)]),d=performance.now()-e}const h=r.workingDirectory||process.cwd();(0,cN.configureVendoredTreeSitterWorkspaceDir)(h);for(const e of r.dirs??[])(0,cN.configureVendoredTreeSitterWorkspaceDir)(e);const p=(0,Zs.Rv)((0,o.homedir)(),h),f={hostProjectDir:p,settings:{includeProjectRules:OO(c,"project"),subagentsService:new GO(r.customSubagents??[])}};let m;const g="win32"===process.platform?"rg.exe":"rg",w=process.env.CURSOR_RIPGREP_PATH;m=w&&(0,s.isAbsolute)(w)?w:(0,lN.hQ)({binaryName:g,excludedWorkspaceDir:h}),m||(m=(0,ri.xS)()),m&&(0,ri.J)(m);let y,v,b={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{y=(0,aN.KU)(r.apiKey,r.teamId);const e=(0,Dn.createClient)(oO.I,y),t=function(e){let t=fN.get(e);return t||(t=mN(e),fN.set(e,t),t.then((r=>{r===pN&&fN.get(e)===t&&fN.delete(e)}),(()=>{fN.get(e)===t&&fN.delete(e)}))),t}(r.apiKey);v=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};b=new n$(new e$(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===l?{}:{hostMcpBridgeUrls:l},isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hN.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const S=performance.now(),k=r.apiKey?await(0,ri.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,_=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=IN(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,ri.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,lN.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,ri.St)({sandboxBinaryPath:r})}(t),!(0,ri.K3)(void 0,{ctx:e.initializationCtx}))throw new BF.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,ri.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:h,perUserSandboxPolicy:k,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,E=performance.now()-S,x=_?.defaultSandboxPolicy,P=_?.defaultSandboxPolicySources,I=IN(x),R=performance.now(),T=(()=>{const e=[],t=new Set;for(const n of[h,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),A={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},$=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=DO(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,ri.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new ry,h=new ll(d,a,n),p=new HO,f=new qO,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new WO(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=OO(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=_||OO(i,"project")||OO(i,"user")||b,x=OO(i,"project")||OO(i,"user")||OO(i,"mdm"),P=OO(i,"team"),I=P&&void 0!==e.dashboardTransport,R=OO(i,"project")||OO(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:OO(i,"project"),includeUserMcp:OO(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>UO({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:A$({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:fO({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:nO({includeProjectHooks:OO(i,"project"),includeUserHooks:OO(i,"user"),includeEnterpriseHooks:OO(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:iO({includeProjectExtensibility:OO(i,"project"),includeUserExtensibility:OO(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:CO({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=>new zO(new oT(e)),createSessionMcpLease:(t,r)=>A$({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{const r=w??new BO;return{pendingDecisionStore:r,fileChangeTracker:new Uw(t),permissionsService:new dP(h,r,g,a,t,e.respectAdminControls??!1)}}}),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 tO(new KD(e.resources,n.hookExecutor,(()=>function(e,t){const r=XD(t,QD,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:XD(t,QD,"generationId","generation_id")??r,model:XD(t,QD,"model")??"unknown",...ze({modelId:XD(t,QD,"modelId","model_id"),modelParams:XD(t,eO,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new GO(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Rg([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return c$.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:h,...void 0!==T?{dirs:T}:{},projectDir:p,teamSettingsService:b,initializationCtx:a,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:x,defaultSandboxPolicySources:P,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new xN:void 0,getNetworkAllowlistInfo:I?()=>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,ri.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,ri.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(b,(0,o.homedir)(),h):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_N,getPowershellUtf8Options:async()=>{if(void 0===v)return A;try{const e=await v;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return A}},isLinkSharedPaymentTokenLogRedactionEnabled:wN(v),respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),M=performance.now()-R;let D,O;return(0,nF.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(d),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(M),load_sandbox_policy_ms:Math.round(E),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,c$.ni)(CN,(async()=>{const s=(0,i.VI)((0,ye.q6)().withName("sdk.run").with(C._O,EN)),[a,c]=s.ctx.withCancel(),l=t.sessionId??(0,Mn.C)(),u=t.mcpServersOverride,d=void 0===(p=t.customTools)?[]:Object.entries(p).map((([e,t])=>({clientKey:Nt,providerIdentifier:Nt,toolName:e,name:`${Nt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??NF,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:jF(t.annotations)},source:"internal"})));var p;let m;const g={...f,workspace:t.fileSystemWorkspace},w=void 0===t.fileSystem?void 0:(y=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),v=y,(0,GF.VL)({"/":v,[JF]:(0,VF.Om)()}));var y,v;m=await $.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:d,...void 0===w?kN(t.sessionResources):iN(w,g)});const b=new Map;try{const s=m.resources.wrapped;bN(m,t.customTools),void 0!==w&&qF(m.resources.base);const i=t.blobStore??new Tn.ve;let p=t.initialState??new qr.Y9z({});const f=void 0!==t.model?new tF.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new tF.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,v=Array.isArray(y)?y.map((e=>{const t=(0,Mn.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,aN.v8)(r);return new rF.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=v.length>0?new rF.xv({selectedImages:v}):void 0,C=function(e){switch(e){case"agent":return qr.xyI.AGENT;case"plan":return qr.xyI.PLAN;default:return}}(t.mode),E=!0===e.summarize?new qr.QFf({action:{case:"summarizeAction",value:new qr.Scs}}):new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:e.text,selectedContext:_,...void 0!==C?{mode:C}:{}})})}}),x={sendUpdate:async(e,t)=>{const r=dF(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return Yr(e.id);case"webFetchRequestQuery":return tn(e.id);case"switchModeRequestQuery":return on(e.id);case"askQuestionInteractionQuery":return nn(e.id,new $o.tz({result:{case:"rejected",value:new $o.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return an(e.id,new Gr.bK({result:{case:"success",value:new Gr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return cn(e.id,new Oo.r$({result:{case:"success",value:new Oo.JH}}));case"replaceEnvArgs":return ln(e.id,new Do.dV({result:{case:"failure",value:new Do.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return un(e.id,new Mo.HL({result:{case:"error",value:new Mo.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return dn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return hn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return pn(e.id,e.query.value.args?.description);case void 0:throw new BF.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new BF.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(D!==t.apiKey||!O){await Promise.all([(0,aN.ly)(t.apiKey),(0,aN.mU)(t.apiKey)]);const e=(0,aN.KU)(t.apiKey,r.teamId),n=Ks((0,Dn.createClient)(eF.N,e),{injectTraceHeaders:!0});O=new Us(n),D=t.apiKey}const P=(0,aN.Vh)(O,(()=>{const e=(0,aN.KU)(t.apiKey,r.teamId),n=Ks((0,Dn.createClient)(eF.N,e),{injectTraceHeaders:!0}),o=new Us(n);return O=o,D=t.apiKey,o})),I=function(e){return{...void 0!==e.allowedTools?{[yN.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yN.VJ]:e.disallowedTools.join(",")}:{}}}(t),R=new YO({agentClient:P,getResources:async({agentId:e})=>{let r=b.get(e);return r||(r=await $.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:d,...void 0===w?kN(t.subagentInherit):iN(w,g)}),bN(r,t.customTools),void 0!==w&&qF(r.resources.base),r.resources.base.register(yn,T),r.resources.base.register(vn,A),r.resources.base.register(bn,M),b.set(e,r)),r.resources.wrapped},mcpTools:d,workspacePath:h,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==w)&&Object.keys(I).length>0?{headers:I}:{},onSessionReleased:e=>{const t=b.get(e);t&&(t.dispose(),b.delete(e))}}),T=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 mn.vS({result:{case:"error",value:new mn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new mn.vS({result:{case:"error",value:new mn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new mn.vS({result:{case:"success",value:new mn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new mn.vS({result:{case:"success",value:new mn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof Qr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof wn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new mn.vS({result:{case:"error",value:new mn.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}}}(R),A=(k=R,{execute:(e,t)=>k.awaitBackgroundRunBounded(e,t)}),M=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(R);m.resources.base.register(yn,T),m.resources.base.register(vn,A),m.resources.base.register(bn,M);const F=$.services.hooksRuntime,N="object"==typeof(S=F)&&null!==S&&"workspacePath"in S&&"string"==typeof S.workspacePath&&"createSessionRuntime"in S&&"function"==typeof S.createSessionRuntime?F:void 0,j=void 0!==N&&void 0===w&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ke.sessionStart)||t.hooksConfigLease.hasHookForStep(ke.sessionEnd)||t.hooksConfigLease.hasHookForStep(ke.stop)||t.hooksConfigLease.hasHookForStep(ke.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(ke.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),is_background_agent:!1},r=await n.executeHookForStep(ke.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){c$.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(ke.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?ze(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(ke.sessionEnd,r)}catch(e){c$.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(ke.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(ke.beforeSubmitPrompt,t)}catch(e){c$.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(ke.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(ke.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(ke.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(ke.stop,t)}catch(e){c$.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(ke.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(ke.stop,t)}catch(e){c$.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:N,sessionState:m.state,metadata:m.metadata}):void 0,L=new ZO({workspacePath:h,conversationId:l,blobStore:i}),U=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new a$;let a;const c=new Map,l=(e,t)=>{const r=c.get(e);void 0!==r&&(c.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let u;const d=[],h=e=>{for(const t of d.splice(0))t.resolve(e)},p=()=>{if(0===d.length)return;const e=d.map((e=>e.text)).join("\n\n");return h("complete_delivered"),f$(e)},f=r.interactionListener,m={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:c.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):(c.delete(t),s.resolve(e))}}await f.sendUpdate(e,t)},query:(e,t)=>f.query(e,t),...void 0!==f.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>f.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==f.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>f.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let g=r.initialState;const w={async handleCheckpoint(e,t){g=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>g};let y="completed";const v=Date.now(),b=u$(function(e,t){if((0,Tn.TU)(t))return t;const r=d$.get(e);if(void 0!==r)return r;const n=(0,Tn.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return d$.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=p$(r,0,h$(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw y="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==y)throw e;c$.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,d=0;for(;s;){const e=p$(r,d,h$(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){c$.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,Mn.C)();try{await r.agentClient.run(o,g,s,void 0,m,r.resources,r.blobStore,i,w,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:b,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw y=m$(t)?"aborted":"error",g$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...c.keys()])l(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw y="error",e}const f="string"==typeof t?t.trim():"";let v;if(f.length>0)v=f$(f);else{const t=new AbortController;u=t;try{v=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw y=o.signal.aborted||m$(r)?"aborted":"error",g$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{u=void 0}void 0===v?v=p():h("revert_to_followup")}void 0!==v?(d+=1,i.resetStream(),s=v):s=void 0}})().finally((async()=>{h("revert_to_followup");const e=Date.now()-v;try{await(n?.onSessionEnd?.(y,e))}catch(e){c$.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){c$.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=u;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{d.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,Mn.C)(),n=new Promise((e=>{const t=setTimeout((()=>{l(r,"revert_to_followup")}),15e3);t.unref?.(),c.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new qr.QFf({action:{case:"injectContextAction",value:new qr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new qr.oW$({userMessage:new qr.RGk({messageId:(0,Mn.C)(),text:e})})}})}})),await n}catch(e){return l(r,"revert_to_followup"),c$.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,E,{agentClient:P,interactionListener:x,resources:s,blobStore:i,initialState:p,conversationId:l,mcpTools:d,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:f,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(I).length>0?{headers:I}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:j,async nextAction(e,t){const r=await R.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new qr.QFf({action:{case:"backgroundTaskCompletionAction",value:new qr.Kwc({completions:e.map((e=>new qr.KFq({taskId:e.agentId,kind:qr.aZc.SUBAGENT,status:"success"===e.status?qr.uHL.SUCCESS:"aborted"===e.status?qr.uHL.ABORTED:qr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){p=e,L.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),B=U.done.finally((async()=>{try{await R.awaitBackgroundWorkers()}finally{await L.waitForPendingWrites().catch((()=>{}));for(const e of b.values())try{await e.dispose()}catch(e){hN.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}b.clear(),await m.dispose()}})).catch((e=>{throw e}));return{abort(){U.abort(),c()},done:B,steer:e=>U.steer(e)}}catch(e){for(const e of b.values())try{await e.dispose()}catch{}throw b.clear(),await m.dispose(),e}var S,k})),async reload(){await $.reload()},async dispose(){await $.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)},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>q,ME:()=>L,_N:()=>H,b6:()=>j,bi:()=>P,mD:()=>A,vc:()=>O});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=F(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<=I&&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}}(F(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=F(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=F(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=F(e);return v.test(t)||function(e){const t=F(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=F(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=F(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(R.has(e))return R.get(e);R.size>=I&&R.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=`${F(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 R.set(e,t),t}const I=2048,R=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("*")&&F(s)===F(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=N(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!F(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(F(r.hostname)!==F(o))return}return r}}function O(e,t){if(A(e,t))return!0;let r;return T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=N(t),T.set(t,r)),!!r&&h(r.hostname,e)}function F(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function N(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 j(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function L(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=j(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(F(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 U(e){const t=e?.trim();return t&&t.length>0?t:void 0}function B(e){return U(e)?.toLowerCase()}function W(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function H({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=U(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=>function(e,t){const r=B(e.builtinServer),n=B(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=U(e.command),s=U(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&&O(s,t.url);return i&&a}(e,t)))}(c,t),d=W(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||W(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!==U(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!==U(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:()=>Yr,Ls:()=>d,SandboxUnsupportedError:()=>Ft,J:()=>_,St:()=>jt,Fn:()=>Qr,ue:()=>o,r5:()=>he,oG:()=>Rr,Ko:()=>P,CG:()=>je,W1:()=>V,G6:()=>Xr,_B:()=>Ie,OK:()=>xe,$b:()=>Pe,K3:()=>Bt,tv:()=>Oe,wG:()=>qe,fZ:()=>Ge,s9:()=>Ue,XX:()=>He,T6:()=>Te,Po:()=>Re,$6:()=>Me,l7:()=>Fe,xS:()=>k,resolveSandboxPolicyForWorkspace:()=>Je,spawnInSandbox:()=>Lt,Xw:()=>x});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function i(e){const t={...e};for(const e of s)delete t[e];return t}const a=[["core.quotePath","false"]];function c(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=y(e,r);if(p.existsSync(n))return v(n,t,r)}for(const o of n){const n=y(`${e}${o}`,r);if(p.existsSync(n))return v(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:h.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:h.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 b;const S=["/usr/local/bin","/usr/bin","/bin"];function k(){const e=v("rg",[]).cmd;return"rg"!==e?e:void 0}function _(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");b=e}function C(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 E(e,t){const r=(0,h.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=C(e);return void 0!==t?e[t]??"":""}(e).split(h.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=S),function(e,t){const r=C(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(h.delimiter))}function x(e){return b&&(0,h.isAbsolute)(b)?{...E(e,b),CURSOR_RIPGREP_PATH:b}:e}function P(){if(!b)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return b}const I="win32"===process.platform;function R(e){return!I&&!!e?.SUDO_ASKPASS}function T(e){return R(e)?"alias sudo='sudo -A'; ":""}function A(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 M=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function D(e){M.some((t=>$(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function O(e){$(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const F="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",N=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],j=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${N.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${F}";; esac; `,L=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${N.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${F}" } else { $env:MAVEN_OPTS = '${F}' }\n}`;var U=r("node:crypto?8af2"),B=r("node:os"),W=r("../utils/dist/workspace-paths.js"),H=r("../utils/dist/test-resets.js");let q;function z(e,t){const r=(0,p.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function G(e){try{(0,p.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function V(e){return K(e,{create:!1})}function K(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,h.join)((0,B.tmpdir)(),`cursor-sandbox-${(0,W.r_)((0,h.resolve)(e))}`);try{for(const e of[n,(0,h.join)(n,"tmp")])if(t&&G(e),!z(e,r))return;return n}catch{return}}(0,H.J)((function(){q=void 0}));const J='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function Z(e=(0,h.join)((0,B.tmpdir)(),"cursor-sandbox-cache",function(){return q||(q=(0,U.randomBytes)(16).toString("hex")),q}())){return{NPM_CONFIG_CACHE:(0,h.join)(e,"npm"),PNPM_STORE_PATH:(0,h.join)(e,"pnpm-store"),GOCACHE:(0,h.join)(e,"go-build"),GOMODCACHE:(0,h.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,h.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,h.join)(e,"pip"),UV_CACHE_DIR:(0,h.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,h.join)(e,"bun"),YARN_CACHE_FOLDER:(0,h.join)(e,"yarn"),npm_config_devdir:(0,h.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,h.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,h.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,h.join)(e,"turbo"),GRADLE_USER_HOME:(0,h.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,h.join)(e,"conda"),POETRY_CACHE_DIR:(0,h.join)(e,"poetry"),GEM_SPEC_CACHE:(0,h.join)(e,"gem-specs"),BUNDLE_PATH:(0,h.join)(e,"bundle"),COMPOSER_HOME:(0,h.join)(e,"composer"),HOMEBREW_CACHE:(0,h.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,h.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,h.join)(e,"nx"),NUGET_PACKAGES:(0,h.join)(e,"nuget"),CCACHE_DIR:(0,h.join)(e,"ccache"),CP_HOME_DIR:(0,h.join)(e,"cocoapods")}}var X=r("node:fs/promises"),Q=r("node:child_process"),Y=r("node:string_decoder"),ee=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),te=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class re extends Error{constructor(e,t,r,n,o,s){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=s,this.command=r,this.args=n,"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,re)}}function ne(e,t,r){r=r??{};let n=new ee.Observable((n=>{const{encoding:o,timeout:s,...i}=r,{cmd:a,args:c}=v(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const u=(0,Q.spawn)(a,c,i);r.processInfo&&void 0!==u.pid&&(r.processInfo.pid=u.pid);let d=null;s&&s>0&&(d=setTimeout((()=>{u.killed||u.kill();const e=new re(`Process timed out after ${s}ms`,-1,a,c);n.error(e)}),s));const h={stdout:new Y.StringDecoder(o||"utf8"),stderr:new Y.StringDecoder(o||"utf8")},p=t=>o=>{if(o.length<1)return;let s;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);try{s="string"==typeof o?o:h[t].write(o)}catch{s=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}s.length>0&&n.next({source:t,text:s})},f=e=>{const t=h[e].end();t.length>0&&n.next({source:e,text:t})},m=new ee.Subscription;if(l)if(u.stdin){const e=u.stdin;m.add(l.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let g=null,w=null,y=!1;if(u.stdout){const e=new ee.AsyncSubject;w=e,u.stdout.on("data",p("stdout")),u.stdout.on("close",(()=>{f("stdout"),e.next(!0),e.complete()}))}else w=(0,ee.of)(!0);if(u.stderr){const e=new ee.AsyncSubject;g=e,u.stderr.on("data",p("stderr")),u.stderr.on("close",(()=>{f("stderr"),e.next(!0),e.complete()}))}else g=(0,ee.of)(!0);return u.on("error",(e=>{y=!0,d&&clearTimeout(d),n.error(e)})),u.on("close",(e=>{y=!0,d&&clearTimeout(d);const t=(0,ee.merge)(w,g).pipe((0,te.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new re(`Process failed with exit code: ${e}`,e,a,c);n.error(t)}))})),m.add(new ee.Subscription((()=>{y||(d&&clearTimeout(d),u.kill())}))),m}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;n=n.pipe((0,te.L5)({count:e,delay:(e,r)=>{if(e instanceof re&&0!==e.exitCode)return(0,ee.timer)(t);throw e}}))}return r.split?n:n.pipe((0,te.Tj)((e=>e?.text)))}function oe(e,t,r){return r?.split?(n=ne(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof re){const n=new re(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof re){const t=new re(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(ne(e,t,{...r??{},split:!1}));var n}var se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const ie=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ae=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],ce=(e,t)=>t.flatMap((t=>ae.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),le={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},ue=e=>[...ie,...le[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),de=[{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"},...ue("linux"),...ce("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"},...ue("darwin"),...ce("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 he(e=process.platform,t=B.default.homedir(),r={}){const n=[];for(const o of de){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,h.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,p.lstatSync)(s).isFile();break;case"home-dir":e=(0,p.lstatSync)(s).isDirectory();break;case"bundled":e=(0,p.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const pe=[{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:"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"}];function fe(e){const t=pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function me(e){const t=pe.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}pe.filter((e=>"git"===e.type)).map((e=>e.pattern)),pe.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const ge=[];let we=null,ye=null;let ve=null;const be=new Map;const Se="win32"===process.platform||"darwin"===process.platform;function ke(e){if(!e.endsWith(h.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function _e(e){return e.endsWith(h.sep)?e:e+h.sep}function Ce(e,t){const r=ke(t);if(Se){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(_e(n))}return e===r||e.startsWith(_e(r))}function Ee(e,t){const r=ke(e);return Se?(0,h.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,h.relative)(r,t).replace(/\\/g,"/")}async function xe(e,t){if(Ce(e,t)){const r=Ee(t,e);if((null===we&&(we=se({ignoreCase:!0}),we.add(pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),we).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=be.get(e);if(t)return t;const r=await(0,X.stat)((0,h.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return be.set(e,t),t}const n=await async function(e){try{const t=await oe("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,h.dirname)((0,h.resolve)(e,t.trim()))}catch{return null}}(e),o={isWorktree:!0,gitDirParent:n??e};return be.set(e,o),o}(t);if(Ce(e,n)){const t=Ee(n,e);if((null===ye&&(ye=se({ignoreCase:!0}),ye.add(pe.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ye).ignores(t))return!0}if(r&&Ce(e,t)&&".git"===Ee(t,e))return!0;for(const t of function(){if(null!==ve)return ve;const e=B.default.homedir(),t=[];for(const r of pe)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,h.join)(e,r.pattern))}return ve=t,t}())if(Ce(e,t))return!0;return!1}function Pe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ie(e){return void 0!==e&&"allow"===e.default}function Re(){return{version:1,default:"deny"}}function Te(){return{version:1,default:"allow"}}var Ae=r("../utils/dist/path-utils.js");function $e(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 Me(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:$e(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function De(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","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 Oe(e,t){const r=await async function(e,t){try{const r=await(0,X.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==De(n))return{success:!1,error:`Invalid sandbox policy: ${De(n)??""}`};let o=Me(n);return t&&(o=Fe(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 Fe(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ae.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ae.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ae.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var Ne=r("../utils/dist/safe-spawn-cwd.js");function je(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Le(...e){return e.some((e=>!0===e))}function Ue(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ze(e));return[...t]}const Be=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]function(...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=ze(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ze);let r=new Set(t[0].map(ze));for(let e=1;en.has(e))))}return[...r]}(...e);function He(...e){return Be.merge(...e)}function qe(...e){return We(...e)}function ze(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Ge(...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 Ve(...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)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function Ke(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Je(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,Ne.$f)(e))return Ze(t,{workspaceDir:e});const n=r.stat??X.stat,o=r.spawnPromise??oe,s=await n((0,h.join)(e,".git")).then((e=>e),(()=>null)),i=s?.isFile()??!1,a=null!==s;if("workspace_readwrite"===je(t)){let r=e;if(i){const n=await o("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,h.resolve)(e,t.trim())),(()=>null));if(n){r=(0,h.dirname)(n);const o=t.perRepo,s=o?.ignoreMapping;t={...t,perRepo:{...o,type:"workspace_readwrite",additionalReadwritePaths:[...o?.additionalReadwritePaths??[],n],ignoreMapping:s,writeProtectionMapping:Ve(o?.writeProtectionMapping,me(e))}}}}if(a)return Ze(t,{workspaceDir:e,gitDirParent:r})}return Ze(t,{workspaceDir:e})}function Ze(e,t){return function(e,t){const r=function(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}(e);if(void 0===r)return tt({},t);switch(r){case"workspace_readwrite":return tt(Qe(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ye(e,t),o={policy:et({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,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Qe(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:et({type:"insecure_none",allowlistEscalated:Le(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Ke(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Le(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Ke(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Qe(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Xe(e,t){return e?.type===t}function Qe(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Xe(r,t)?r:void 0,perRepo:Xe(n,t)?n:void 0,teamAdmin:Xe(o,t)?o:void 0}}function Ye(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!==ge.length)return{version:1,deny:[...ge]}}(),r=B.default.homedir(),n=[];for(const e of pe)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,h.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:fe(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")},p=Le(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 f=Le(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=Ke(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=Ke(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?Ue(s.additionalReadPaths):Ue(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=Ue(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=Ge(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=Ke(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=Le(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=Ke(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=Ve(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=function(e){const t=pe.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??i);return{disableTmpWrite:p||void 0,networkPolicyStrict:f,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:Ve(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function et(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 tt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ye(e,t),a=Ue(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:et({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,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var rt=r("../utils/dist/workload-spawn.js"),nt=r("../context/dist/logger.js"),ot=r("../context/dist/core.js");const st=Q.execFile,it=new WeakMap;function at(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}let ct=0;function lt(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?h.resolve(e):h.resolve(h.join(B.homedir(),".cursor","sandbox-policies"))}();p.mkdirSync(e,{recursive:!0,mode:448});try{p.chmodSync(e,448)}catch{}const t=Date.now();return t-ct>=9e5&&(ct=t,function(e){let t;try{t=p.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=h.join(e,n);try{const e=p.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&p.unlinkSync(t)}catch{}}}(e)),e}function ut(e){const t=lt(),r=U.randomBytes(8).toString("hex"),n=h.join(t,`sandbox-policy-${r}`);return p.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const dt="darwin"===process.platform,ht="linux"===process.platform,pt=(0,nt.h)("shell-exec:sandbox");function ft(e){const t=lt();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let mt,gt=!0,wt=!1;function yt(){return mt}function vt(e){"linux"===process.platform&&Object.assign(e,x(e))}let bt=null,St=null,kt=null,_t=null,Ct=!1,Et=null;function xt(e){return{...e,additionalReadonlyPaths:ft(e.additionalReadonlyPaths)}}function Pt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return Mt(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,p.existsSync)(r)&&(0,p.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=function(e,t=e=>p.existsSync(e)){if((0,Ne.$f)(e))return!0;let r=h.resolve(e);for(;;){try{if(t(h.join(r,".git")))return!0}catch{}const e=h.dirname(r);if(e===r)return!1;r=e}}(r),s=!ht||o?t??{}:{},i={...n};for(const[e,t]of Object.entries(s))i[e]?i[e]=[...i[e],...t]:i[e]=t;if(0!==Object.keys(i).length)return Mt(i)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=gt;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=P()}catch{}for(const o of he(e,B.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=B.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=h.join(B.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=h.basename(e);if((o.includes("*")||o.includes("?"))&&(e=h.dirname(e)),!e||"."===e)continue;const s=h.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Pe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function It(e){const t={sandbox:e};return ht&&function(){const e=wt;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Rt(e){if(null!==bt)return bt;try{const t=yt();return pt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(bt=p.existsSync(t),bt?pt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(bt)}`):(St=new Error(`Sandbox binary not found at ${t}`),pt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),bt):(St=new Error("Sandbox binary path was not configured"),bt=!1,pt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return St=t instanceof Error?t:new Error(String(t)),bt=!1,pt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Tt(e){if(null!==_t)return _t;const t=e??(0,ot.q6)();if(pt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Rt(t)){const e=St?.message||"Binary check failed";return kt=e,pt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),_t=!1,_t}if("win32"===process.platform)return kt="Windows sandbox helper only provides network proxy, not filesystem isolation",pt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),_t=!1,_t;if("darwin"===process.platform)return kt=null,pt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),_t=!0,_t;const{binaryPath:r,args:n,env:o}=function(e,t){const r=It(Pt(xt({type:"workspace_readwrite"}),t)),n=String(yt());pt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),pt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return vt(o),{binaryPath:n,args:["--policy",ut(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,rt.D9)(Q.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:At,env:o,shell:!1});const s=Date.now()-e;return kt=null,pt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),_t=!0,_t}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return pt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),pt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&pt.error(e,`[sandboxPreflight] Stderr: ${o}`),kt=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"}`,_t=!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,H.J)((function(){_t=null,Ct=!1,Et=null,kt=null,bt=null,St=null}));const At=15e3;function $t(e,t=[],r={},n){const s=(0,ot.q6)();if(r.env=o(r.env),!Rt(s))throw new Error(`Sandbox binary not available: ${St?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,rt.D9)(Q.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let c=e,l=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",l=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",l=["-c",`${e} ${t.join(" ")}`]));const u=Pt(xt(n),a),d=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return K(e.cwd,{create:!0})}(u);d&&(u.additionalReadwritePaths=[...u.additionalReadwritePaths??[],d]);const p=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Pe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),f=It(u);void 0!==p&&(f.networkPolicy=p),!1===n.networkPolicyStrict&&(f.networkPolicyStrict=!1);const m=["--policy",ut(JSON.stringify(f)),"--",c,...l],g=o(process.env),w={..."linux"===process.platform?i(g):g,..."linux"===process.platform&&r.env?i(r.env):r.env,CURSOR_SANDBOX:"native"};if(vt(w),d){const e=function(e,t,r){const n=function(e){const t=(0,h.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,h.join)(t,"sh-")}}(e);if(r){const r=Z();for(const[o,s]of Object.entries(Z(e)))t[o]===r[o]&&(n[o]=s)}return n}(d,w,n.enableSharedBuildCache);Object.assign(w,e),w.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),w.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const y={cwd:r.cwd||s,env:w,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,rt.D9)(Q.spawn,String(yt()),m,y);return dt&&t.pid&&function(e,t){it.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,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function Mt(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Dt(t):t;o[e]=r;const n=Ot(e);n!==e&&(o[n]=r)}return o}function Dt(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ot(e,t){if((0,Ne.$f)(e))return e;try{return(t??p.realpathSync)(e)}catch{return e}}class Ft extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Nt="darwin"===process.platform;function jt(e){!function(e){P();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;mt||(mt=t),void 0!==r&&(gt=r),void 0!==n&&(wt=n)}(e)}function Lt(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...Z(),...r.env}}),"insecure_none"!==n.type){if(Tt())return $t(e,t,r,n);const o=kt;throw new Ft(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Q.spawn,spawnWorkload:rt.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function Ut(e){return Nt?async function(e){const t=it.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,rt.D9)(st,"/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:at(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:at(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 Bt(e,t){if(Nt)try{(0,p.accessSync)("/usr/bin/sandbox-exec",p.constants.X_OK)}catch{return!1}return Tt(t?.ctx)}var Wt=r("node:stream"),Ht=r("../context/dist/otel.js"),qt=r("../utils/dist/writable-iterable.js");const zt="--",Gt='builtin eval "$1" 3<&- 4>&-',Vt=50,Kt=262144;class Jt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Vt,this.maxBufferedBytes=t?.maxBufferedBytes??Kt}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 Jt(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([Xt(e.stdout,r,t),Qt(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 Xt(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 Qt(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Yt;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Yt||(Yt={}));const er={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function tr(e,t,r,n={spawn:Q.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function rr(e,t=[],r={},n,o){const s=Lt(e,t,{...r,env:x(r.env??process.env)},n);if(o){const e=function(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}({platform:process.platform,detached:!0===r.detached}),t=()=>{if(!s.pid)return;tr(s,e,"SIGTERM");const t=setTimeout((()=>{!s.killed&&s.pid&&tr(s,e,"SIGKILL")}),1e3);"process_group"!==e&&s.once("exit",(()=>{clearTimeout(t)}))};o.aborted?t():(o.addEventListener("abort",t,{once:!0}),s.once("exit",(()=>{o.removeEventListener("abort",t)})))}return s}function nr(e){const t=[];return e?.on("data",(e=>{t.push(e)})),()=>Buffer.concat(t).toString("utf8")}function or(e){e?.on("error",(()=>{}))}const sr="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 ir(e,t){return 126===e&&""===t}function ar(){return"win32"!==process.platform}function cr(e,t){const r=e.stdio.at(5);r instanceof Wt.default.Writable&&(or(r),r.end(`${t}\0`))}function lr(e,t){e&&(or(e),e.write(t),e.end())}function ur(e,t){if(!e)return;or(e);const r=new Y.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 dr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function hr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function pr(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 fr="__CURSOR_BASH_STATE_START__",mr="__CURSOR_BASH_STATE_END__";var gr=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 wr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=v("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:v("bash",[]).cmd}function yr(e){if("win32"!==process.platform)return e;const t=h.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===h.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function vr(e){const t=e.pipeStdin?Gt:`${Gt} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?sr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+J+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class br{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new br(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;h.default.resolve(t)===h.default.resolve(this.cwd)&&(this.cwd=void 0===r||h.default.resolve(r)===h.default.resolve(t)||(0,Ne.A)(r)?(0,Ne.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{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}(n,(0,Ht.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,qt.Jt)(),a=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...er,...e?.env};return c(n),"win32"===t&&(D(n),O(n)),n}(r),u=T(l),d=this.useFileStateTransport,p=!d&&!this.commandPipeUnreadable;let f,m,g;if(d){f=await(0,X.mkdtemp)(h.default.join(B.default.tmpdir(),"cursor-bash-state-")),m=h.default.join(f,"state-in"),g=h.default.join(f,"state-out"),await(0,X.writeFile)(m,this.state,"utf8"),await(0,X.writeFile)(g,"","utf8").catch((()=>{}));const e=yr(m),t=yr(g);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const w=function(e){return["-O","extglob","-c",e.script,zt,...void 0===e.command?[]:[e.command]]}({script:vr({pipeCommand:p,useFileTransport:d,sudoAliasInjection:u,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?j:""}),command:p?void 0:t}),y=wr(this.userTerminalHint);if(!y)throw new Error("Can't find Bash");const v=r?.sandboxWorkspaceRoot??a,b=(await Je(v,r?.sandboxPolicy)).policy,S="insecure_none"!==b.type?{...b,sandboxWorkspaceRoot:v}:b;let k="";const _=async()=>{if(d){if(!g)return void(k=this.state);try{k=await(0,X.readFile)(g,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),k=this.state}}},C=async()=>{if(f)try{await(0,X.rm)(f,{recursive:!0,force:!0})}catch{}};let E;(0,Ne.$Y)(a)&&(0,Ht.HF)(o.ctx,Ne.yo);try{E=rr(y,w,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:a,detached:!0},S,r?.signal)}catch(e){throw await C(),e}E.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:E.stdin??void 0,pid:E.pid})}catch(e){}}));const x=Zt({stdout:E.stdout,stderr:E.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});E.on("error",(async e=>{if((0,Ne.fK)(e,a)){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await C(),i.throw(e)}));let P=null,I=null,R=null,A=!1;const $=async e=>{if(A)return;if(A=!0,R&&(clearTimeout(R),R=null),(0,Ht.HF)(o.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await C(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,Ne.wz)({exitCode:P,stdoutBytes:x.stdoutBytes,stdoutPrefix:x.stdoutPrefix,cwd:a})&&""===k;if(t&&x.dropHeldStdout(),await x.flush(),p&&ir(P,k)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await C(),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,Ne.Vn)(a))}if(!r?.signal?.aborted){await _();const e=`${fr}\n`,t=`${mr}\n`;if(k.startsWith(e)&&k.endsWith(t)){let t=k.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=dr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(S.captureDenies)try{const e=await Ut(E);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:P,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await C()};E.on("exit",((e,t)=>{P=e,I=t;const n=r?.closeTimeout??5e3;n>0&&(R=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),$(!1)}),n))})),E.on("close",(async()=>{await $(!0)}));const M=E.stdio[3],F=E.stdio[4],N=M instanceof Wt.default.Writable?M:null,L=F instanceof Wt.default.Readable?F:null;p&&cr(E,t),d||(lr(N,this.state),ur(L,(e=>{k+=e}))),yield*i}catch(e){n.error=e,n.hasError=!0}finally{gr(n)}}}async function Sr(e){const t={...process.env,...er,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=wr(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const s=rr(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal),i=nr(s.stdout);s.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=pr(hr(i(),r),fr,mr)??`${process.cwd()}\n`,{cwd:c,rest:l}=dr(a),u="win32"===process.platform,d="win32"===process.platform?process.cwd():c;return new br(d,l,e?.userTerminalHint,u)}var kr=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 _r{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new _r((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={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})}(n,(0,Ht.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{kr(n)}}}const Cr="\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",Er=e=>e.map((e=>`'${e}'`)).join(", "),xr=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $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 $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\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 if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.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; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\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 'either' }\n if ($__cursorFull) {\n # A full window 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 }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\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 # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\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 -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\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 # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\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}\n'@\n if (-not $__cursorHasEncodingDefault) {\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 Get-Content -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 $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\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:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # 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 @(${Er([".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 @(${Er([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${Er([".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 @(${Er([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${Er([".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 }\n }\n} catch { }\n`,Pr=String.raw` ++import s2codeRetryGuard from "../s2code-retry.cjs"; ++import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=305;export const __webpack_esm_ids__=[305];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>RN});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../context/dist/otel.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});class c{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,i.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{a(e)}}}function l(e){return e instanceof Error?e.message:String(e)}function u(e){return"Failed to read skill file: "+l(e)}function d(e){return"Invalid skill frontmatter: "+l(e)}function h(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const p=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function f(e){return e.toLocaleString("en-US")}var m=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const g=102400;function w(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function y({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>g?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=g;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 v(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function b(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$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(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=e.slice(r+1).trim(),c=v(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=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=v(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 S(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 k(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const _=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];var C=r("../context/dist/logger.js"),E=r("../metrics/dist/index.js"),x=r("../proto/dist/generated/agent/v1/exec_pb.js"),P=r("../utils/dist/writable-iterable.js");const I=/https?:\/\/\S+/gi,R=/[)"'<>,.;:\]}]$/;function T(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&R.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(I,T),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const M=(0,C.h)("SimpleControlledExecManager"),D=(0,E.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),O=(0,E.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),F=(0,E.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),N={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 j extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function L(e){return e instanceof j?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class U{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}),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 B{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 x.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class W{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t}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,P.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new x.$Y({message:{case:"heartbeat",value:new x.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new x.$Y({message:{case:"streamClose",value:new x.D9({id:t.id})}})),O.increment(r,1,{exec_case:o})}catch(e){if(e instanceof P.W2)return;F.increment(r,1,{exec_case:o}),await a.write(new x.$Y({message:{case:"throw",value:new x.Fu({id:t.id,error:e instanceof Error?$(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:L(e)})}}))}finally{const e=performance.now()-u;D.histogram(r,e,{exec_case:o}),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:N[s])??`No handler found for server message of type ${s}`;return M.error(e,i,{messageCase:s}),F.increment(e,1,{exec_case:o}),async function*(){yield new x.$Y({message:{case:"throw",value:new x.Fu({id:t.id,error:i})}}),yield new x.$Y({message:{case:"streamClose",value:new x.D9({id:t.id})}})}()}static fromResources(e,t){const r=new W(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}async function H(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}}var q=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},z=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 G=(0,C.h)("ExecutorResource"),V=(0,E.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class K{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=q(n,(0,i.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const a=(0,i.mJ)(s),c=a?new x.Kg(a):void 0,l=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new x.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:c,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await H(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)V.increment(s,1,{hook_event_name:t.hookEventName})}};p(d);let f=this.deserializeResult(d);for(;void 0===f;){const e=await H(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),f=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)p(e)}catch(e){G.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),f}catch(e){n.error=e,n.hasError=!0}finally{z(n)}}}class J{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=q(n,(0,i.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,i.mJ)(o),a=s?new x.Kg(s):void 0,c=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new x.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of c){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{z(n)}}}function Z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function X(e,t,r){return{name:e,symbol:Z(e),remoteImplementation:t,registerControlledImplementation:r}}class Q{constructor(e,t){this.resource=e,this.value=t}}function Y(e,t){return[e,t]}function ee(e,t){return t}class te{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new Q(e,t))}get(e){return ee(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class re{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?ee(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 ne(e){return function(t,r){return new x.Ye({id:t,message:{case:e,value:r}})}}function oe(e){return t=>{if(t.message.case===e)return t.message.value}}function se(e){return function(t,r){const n={case:e,value:r};return new x.yT({id:t,message:n})}}function ie(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ae=X("agent-store-conflict-executor",(e=>new K(e,ne("agentStoreConflictArgs"),oe("agentStoreConflictResult"))),((e,t)=>{t.register(new U(e,ie("agentStoreConflictArgs"),se("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class ce{async execute(e,t){return"ack"===t.op?{kind:"acked",count:0}:"release"===t.op?{kind:"released",count:0}:"noteDeferredEagerWrittenPaths"===t.op?{kind:"noted",count:0}:{kind:"not-applicable"}}}X("agent-store-conflict-notice-executor",(e=>new ce),((e,t)=>{}));const le=X("background-shell-executor",(e=>new K(e,ne("backgroundShellSpawnArgs"),oe("backgroundShellSpawnResult"))),((e,t)=>{t.register(new U(e,ie("backgroundShellSpawnArgs"),se("backgroundShellSpawnResult")))})),ue=X("write-background-shell-input-executor",(e=>new K(e,ne("writeShellStdinArgs"),oe("writeShellStdinResult"))),((e,t)=>{t.register(new U(e,ie("writeShellStdinArgs"),se("writeShellStdinResult")))}));function de(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}const he="local";function pe(e,t){return`${e}:task_progress:${t}`}const fe=X("canvas-diagnostics-executor",(e=>new K(e,ne("canvasDiagnosticsArgs"),oe("canvasDiagnosticsResult"))),((e,t)=>{t.register(new U(e,ie("canvasDiagnosticsArgs"),se("canvasDiagnosticsResult")))}));Error;const me=X("computer-use-executor",(e=>new K(e,ne("computerUseArgs"),oe("computerUseResult"))),((e,t)=>{t.register(new U(e,ie("computerUseArgs"),se("computerUseResult")))})),ge=(X("conversation-search-executor",(e=>new K(e,ne("conversationSearchArgs"),oe("conversationSearchResult"))),((e,t)=>{t.register(new U(e,ie("conversationSearchArgs"),se("conversationSearchResult")))})),X("delete-executor",(e=>new K(e,ne("deleteArgs"),oe("deleteResult"))),((e,t)=>{t.register(new U(e,ie("deleteArgs"),se("deleteResult")))}))),we=X("diagnostics-executor",(e=>new K(e,ne("diagnosticsArgs"),oe("diagnosticsResult"))),((e,t)=>{t.register(new U(e,ie("diagnosticsArgs"),se("diagnosticsResult")))}));var ye=r("../context/dist/core.js");(0,ye.cF)(Symbol("execConversationId"),void 0),(0,ye.cF)(Symbol("execRequestId"),void 0),(0,ye.cF)(Symbol("execBrowserOperationSource"),void 0);const ve=X("fetch-executor",(e=>new K(e,ne("fetchArgs"),oe("fetchResult"))),((e,t)=>{t.register(new U(e,ie("fetchArgs"),se("fetchResult")))})),be=X("git-diff-executor",(e=>new K(e,ne("gitDiffRequest"),oe("gitDiffResponse"))),((e,t)=>{t.register(new U(e,ie("gitDiffRequest"),se("gitDiffResponse")))})),Se=X("grep-executor",(e=>new K(e,ne("grepArgs"),oe("grepResult"))),((e,t)=>{t.register(new U(e,ie("grepArgs"),se("grepResult")))})),ke={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"},_e={PreToolUse:ke.preToolUse,PermissionRequest:null,PostToolUse:ke.postToolUse,UserPromptSubmit:ke.beforeSubmitPrompt,Stop:ke.stop,SubagentStop:ke.subagentStop,SessionStart:ke.sessionStart,SessionEnd:ke.sessionEnd,PreCompact:ke.preCompact,Notification:null},Ce=Object.fromEntries(Object.entries(_e).filter((e=>Ee(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Ee(e){return Object.prototype.hasOwnProperty.call(_e,e)}const xe={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Pe=["Glob"],Ie=["Notification","PermissionRequest"],Re=e=>"string"==typeof e,Te=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ae=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$e=(e,t=[])=>({isValid:e,errors:t});function Me(e,t,r){void 0===e||Re(e)||r.push(`${t} must be a string if provided`)}const De={warn:()=>{},info:()=>{}};function Oe(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?{type:"prompt",prompt:e.prompt,...r}:null:e.command?{type:"command",command:e.command,...r}:null}function Fe(e,t,r=De){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=De){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=xe[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Pe.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=Oe(t,o);e&&n.push(e)}return n}function Ne(e,t=De){const r={};for(const[n,o]of Object.entries(e)){if(!Ee(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ie.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=_e[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=Fe(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}}function je(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}const Le="Agent note: Do not suggest workarounds to the blocked tool.";function Ue(e){return e.includes(Le)?e:`${e}\n\n${Le}`}function Be(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 We(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)))}const He=e=>{const t=[];return Te(e)?$e(!0):(t.push("Expected an object"),$e(!1,t))},qe=e=>{const t=[],r=He(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"),$e(0===t.length,t)};function ze(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 Ge=new Set([ke.sessionStart,ke.beforeSubmitPrompt,ke.preToolUse,ke.postToolUse,ke.postToolUseFailure]);function Ve(e){return"prompt"===e.type}function Ke(e){return"command"===e.type||void 0===e.type}const Je={[ke.beforeShellExecution]:qe,[ke.beforeMCPExecution]:qe,[ke.afterShellExecution]:e=>{const t=He(e);return t.isValid,t},[ke.afterMCPExecution]:e=>{const t=He(e);return t.isValid,t},[ke.beforeReadFile]:e=>{const t=[],r=He(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"),$e(0===t.length,t)},[ke.afterFileEdit]:e=>{const t=He(e);return t.isValid,t},[ke.beforeTabFileRead]:e=>{const t=[],r=He(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"),$e(0===t.length,t)},[ke.afterTabFileEdit]:e=>He(e),[ke.beforeSubmitPrompt]:e=>{const t=He(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||Re(e.additional_context)||r.push("additional_context must be a string if provided"),$e(0===r.length,r)},[ke.stop]:e=>{const t=He(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"),$e(0===r.length,r)},[ke.afterAgentResponse]:e=>{const t=He(e);return t.isValid,t},[ke.afterAgentThought]:e=>{const t=He(e);return t.isValid,t},[ke.sessionStart]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Te(e.env))for(const[t,n]of Object.entries(e.env))Re(t)||r.push(`env key "${t}" must be a string`),Re(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||Re(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||Re(e.user_message)||r.push("user_message must be a string if provided"),$e(0===r.length,r)},[ke.sessionEnd]:e=>{const t=He(e);return t.isValid?$e(!0,[]):t},[ke.preCompact]:e=>{const t=He(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $e(!0,[]);const r=[];if(!Ae(e))return r.push("PreCompact response must be an object"),$e(!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"),$e(0===r.length,r)},[ke.subagentStart]:e=>{const t=He(e);if(!t.isValid)return t;if(!Ae(e))return $e(!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||Re(n.user_message)||r.push("user_message must be a string if provided"),$e(0===r.length,r)},[ke.subagentStop]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];return Ae(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$e(0===r.length,r)},[ke.preToolUse]:e=>{const t=[],r=He(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"),Me(e.additional_context,"additional_context",t),$e(0===t.length,t)},[ke.postToolUse]:e=>{const t=[],r=He(e);return r.isValid?(Me(e.additional_context,"additional_context",t),$e(0===t.length,t)):r},[ke.postToolUseFailure]:e=>{const t=He(e);if(!t.isValid)return t;const r=[];return Me(e.additional_context,"additional_context",r),$e(0===r.length,r)},[ke.workspaceOpen]:e=>{const t=He(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")),$e(0===r.length,r)}},Ze=(e,t,r)=>{const n=function(e,t,r){let n;n=e===ke.preToolUse?function(e,t){if(!at(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(!it(t))return r;const n=ct(e);if(!lt(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),at(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===ke.stop?ut(t,r,"Stop"):e===ke.subagentStop?ut(t,r,"SubagentStop"):t;const o=function(e,t,r,n){if(!Ge.has(e)||!at(r)||void 0!==r.additional_context)return r;const o=at(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!it(r))return;const n=Ce[e];if(void 0===n)return;const o=ct(t);return lt(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);return o}(e,t,r),o=(0,Je[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},Xe=[ke.beforeShellExecution,ke.beforeMCPExecution,ke.beforeReadFile,ke.beforeTabFileRead,ke.subagentStart,ke.preToolUse],Qe=[ke.workspaceOpen];function Ye(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 et(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function tt(e){return Xe.includes(e)}function rt({step:e,command:t,failClosed:r,kind:n}){const o=tt(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:ot(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function nt(e,t){return t}function ot(e,t){return tt(e)?nt(0,{permission:"deny",user_message:t}):e===ke.beforeSubmitPrompt||e===ke.sessionStart?nt(0,{continue:!1,user_message:t}):e===ke.stop?nt(0,{}):void 0}function st(e){try{return{value:JSON.parse(e)}}catch{return}}function it(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function at(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ct(e){if(!at(e))return;const t=e.hookSpecificOutput;return at(t)?t:void 0}function lt(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function ut(e,t,r){if(!at(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return{...n,followup_message:n.reason.trim()};if(!it(t))return n;const o=ct(e),s=lt(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 dt=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function ht(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;e{const t=[];if(!Te(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)"),$e(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Re(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&&(Re(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)=>{Re(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(Re(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),$e(0===t.length,t)},bt=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$e(!1,r);for(let n=0;n{const t=[];if(!Te(e))return t.push("Hooks config must be an object"),$e(!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"),!Te(e.hooks))return t.push("Config hooks must be an object"),$e(!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(ke),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=bt(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $e(0===t.length,t)};var kt=r("../proto/dist/generated/agent/v1/hooks_pb.js");(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,ye.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,ye.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const _t=(0,ye.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),Ct=(0,ye.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function Et(e){return"inExecute"!==e.get(Ct).kind}function xt(e,t){const r=e.get(Ct);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}const Pt=X("hook-executor",(e=>new K(e,ne("executeHookArgs"),oe("executeHookResult"))),((e,t)=>{t.register(new U(e,ie("executeHookArgs"),se("executeHookResult")))})),It=new Set(Object.values(ke));function Rt(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function Tt(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function At(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class $t{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return It.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new x.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??"",...ze(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(ke.preCompact,t);return new x.S1({response:new x.w5({response:{case:"preCompact",value:new kt.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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(ke.subagentStart,t);return new x.S1({response:new x.w5({response:{case:"subagentStart",value:new kt.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??"",...ze(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:Rt(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(ke.subagentStop,t);return new x.S1({response:new x.w5({response:{case:"subagentStop",value:new kt.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ke.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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 x.S1({response:new x.w5({response:{case:"beforeSubmitPrompt",value:new kt.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ke.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(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 x.S1({response:new x.w5({response:{case:"afterAgentResponse",value:new kt.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ke.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new x.S1({response:new x.w5({response:{case:"afterAgentThought",value:new kt.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ke.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...ze(e),status:Rt(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 x.S1({response:new x.w5({response:{case:"stop",value:new kt.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(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(ke.preToolUse,o);return new x.S1({response:new x.w5({response:{case:"preToolUse",value:new kt.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(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(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(ke.postToolUse,o);return new x.S1({response:new x.w5({response:{case:"postToolUse",value:new kt.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!Et(e))return this.skipToolUseStep();const t=r.request.value,n=At(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...ze(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:Tt(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(ke.postToolUseFailure,o);return new x.S1({response:new x.w5({response:{case:"postToolUseFailure",value:new kt.U1({additionalContext:s?.additional_context})}})})}default:return new x.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new x.S1({response:void 0})}}(0,ye.cF)(Symbol("execHookConversationId"),void 0),(0,ye.cF)(Symbol("execHookGenerationId"),void 0),(0,ye.cF)(Symbol("execHookModel"),void 0);const Mt=(0,ye.cF)(Symbol("execHookWorkspaceRoots"),void 0),Dt=X("ls-executor",(e=>new K(e,ne("lsArgs"),oe("lsResult"))),((e,t)=>{t.register(new U(e,ie("lsArgs"),se("lsResult")))})),Ot="cursor-ide-browser",Ft="cursor-dev-control",Nt="custom-user-tools",jt=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Ot,Ft,Nt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Lt(e){return!jt.has(e)}const Ut=new Set([Ft,Ot]);function Bt(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Wt(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 Ht;function qt(e){return void 0===e||void 0===e.serverIdentifiers}function zt(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,ye.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"}(Ht||(Ht={}));const Gt=X("mcp-executor",(e=>new K(e,ne("mcpArgs"),oe("mcpResult"))),((e,t)=>{t.register(new U(e,ie("mcpArgs"),se("mcpResult")))})),Vt=X("list-mcp-resources-executor",(e=>new K(e,ne("listMcpResourcesExecArgs"),oe("listMcpResourcesExecResult"))),((e,t)=>{t.register(new U(e,ie("listMcpResourcesExecArgs"),se("listMcpResourcesExecResult")))})),Kt=X("read-mcp-resource-executor",(e=>new K(e,ne("readMcpResourceExecArgs"),oe("readMcpResourceExecResult"))),((e,t)=>{t.register(new U(e,ie("readMcpResourceExecArgs"),se("readMcpResourceExecResult")))})),Jt=X("mcp-state-executor",(e=>new K(e,ne("mcpStateExecArgs"),oe("mcpStateExecResult"))),((e,t)=>{t.register(new U(e,ie("mcpStateExecArgs"),se("mcpStateExecResult")))})),Zt=X("mcp-allowlist-precheck-executor",(e=>new K(e,ne("mcpAllowlistPrecheckArgs"),oe("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("mcpAllowlistPrecheckArgs"),se("mcpAllowlistPrecheckResult")))}));class Xt extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Qt(e){if(e instanceof Xt)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}const Yt=8388608;var er=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),tr=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function rr(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class cr{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 ar(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new tr.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const lr=X("read-executor",(e=>new K(e,ne("readArgs"),oe("readResult"))),((e,t)=>{t.register(new U(e,ie("readArgs"),se("readResult")))})),ur=X("redacted-read-executor",(e=>new K(e,ne("redactedReadArgs"),oe("redactedReadResult"))),((e,t)=>{t.register(new U(e,ie("redactedReadArgs"),se("redactedReadResult")))})),dr="$file:";const hr=(0,E.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),pr=(0,E.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),fr=(0,E.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"]}),mr=(0,E.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function gr(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${dr}${t}": ${r} A string argument of the form "${dr}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class wr extends Error{constructor(e){super(e.message),this.failure=e}}async function yr(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=>(hr.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new er.iz({result:{case:"error",value:new er.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new wr(gr("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 a=r();if(void 0===a)throw new wr(gr("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,or.xb)(t,(t=>async function(e,t,r,n,o,s){const i=await t.execute(e,new tr.a2({path:r,toolCallId:n,...s?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,n=s&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===n&&"content"!==t.output.case)throw new wr(gr("not_text",r,"the file is not a text file."));if(s&&(fr.increment(e,1,{source:void 0!==n?"vm_digest":"outdated_executor"}),void 0===n))throw new wr(gr("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."));const a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=n??await ar(a??"");if(t.truncated||l>o)throw new wr(gr("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${o} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return{content:a,bytes:l,sha256:c}}case"fileNotFound":throw new wr(gr("not_found",r,"the file does not exist."));case"permissionDenied":throw new wr(gr("permission_denied",r,"reading it was not permitted."));case"rejected":throw new wr(gr("rejected",r,`${i.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":throw new wr(gr("not_text",r,"the file cannot be read as text."));case"error":throw new wr(gr("read_error",r,i.result.value.error));default:throw new wr(gr("read_error",r,"the read returned no result."))}}(e,a,t,n,s,o)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new wr(gr("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 c}(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof wr?e.failure:gr("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(gr("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(dr))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,sr.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,hr.increment(e,1,{route:r,outcome:"expanded"}),pr.record(e,l,{route:r}),mr.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 vr=/\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 br(e,t,r,n){return vr.test(t)?(hr.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${dr}/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 Sr(e){return e.files.map((e=>`"${dr}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class kr{constructor(e,t){this.inner=e,this.getReadExecutor=t}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 yr(e,t,{route:"local",getReadExecutor:this.getReadExecutor});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=br(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 er._Z({content:{case:"text",value:new er.zN({text:Sr(r)})}})):"error"===n.result.case&&(n.result.value.error=br(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const _r=X("mini-swe-agent-bash-executor",(e=>new K(e,ne("miniSweAgentBashArgs"),oe("miniSweAgentBashResult"))),((e,t)=>{t.register(new U(e,ie("miniSweAgentBashArgs"),se("miniSweAgentBashResult")))}));var Cr=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Er=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),xr=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Pr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Ir=X("shell-executor",(e=>new K(e,ne("shellArgs"),oe("shellResult"))),((e,t)=>{t.register(new U(e,ie("shellArgs"),se("shellResult")))})),Rr=X("shell-stream-executor",(e=>new J(e,ne("shellStreamArgs"),oe("shellStream"))),((e,t)=>{t.register(new B(e,ie("shellStreamArgs"),se("shellStream")))})),Tr=((0,ye.cF)(Symbol("optionalPendingPodWrite"),!1),X("write-executor",(e=>new K(e,ne("writeArgs"),oe("writeResult"))),((e,t)=>{t.register(new U(e,ie("writeArgs"),se("writeResult")))})));function Ar(e,t){return new xr.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function $r(e){return{execute:async(t,r)=>new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r.path,error:e,isReadonly:!0})}})}}function Mr(e){return{execute:async(t,r)=>new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function Dr(e){return{execute:async(t,r)=>new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}const Or=X("record-screen-executor",(e=>new K(e,ne("recordScreenArgs"),oe("recordScreenResult"))),((e,t)=>{t.register(new U(e,ie("recordScreenArgs"),se("recordScreenResult")))})),Fr=X("request-context-executor",(e=>new K(e,ne("requestContextArgs"),oe("requestContextResult"))),((e,t)=>{t.register(new U(e,ie("requestContextArgs"),se("requestContextResult")))}));var Nr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const jr=X("shell-allowlist-precheck-executor",(e=>new K(e,ne("shellAllowlistPrecheckArgs"),oe("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("shellAllowlistPrecheckArgs"),se("shellAllowlistPrecheckResult")))})),Lr=X("force-background-shell-executor",(e=>new K(e,ne("forceBackgroundShellArgs"),oe("forceBackgroundShellResult"))),((e,t)=>{t.register(new U(e,ie("forceBackgroundShellArgs"),se("forceBackgroundShellResult")))}));function Ur(e,t){e.hookApprovalRequirement=void 0!==t?new xr.In(t):void 0}function Br(e){return e.hookApprovalRequirement}function Wr(e){return e?.kind===xr.b.FORCE_PROMPT}function Hr(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Wr(e.hookApprovalRequirement))}X("smart-mode-classifier-executor",(e=>new K(e,ne("smartModeClassifierArgs"),oe("smartModeClassifierResult"))),((e,t)=>{t.register(new U(e,ie("smartModeClassifierArgs"),se("smartModeClassifierResult")))}));var qr=r("../proto/dist/generated/agent/v1/agent_pb.js"),zr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Gr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),Vr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Kr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Jr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Zr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Xr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Qr 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 Yr=e=>new qr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Xr.lI({result:{case:"approved",value:new Xr.XJ}})}}),en=(e,t)=>new qr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Xr.lI({result:{case:"rejected",value:new Xr.yc({reason:t??""})}})}}),tn=e=>new qr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Zr.fS({result:{case:"approved",value:new Zr.Hs}})}}),rn=(e,t)=>new qr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Zr.fS({result:{case:"rejected",value:new Zr.m$({reason:t??""})}})}}),nn=(e,t)=>new qr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new qr.zT({result:t})}}),on=e=>new qr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Jr.w$({result:{case:"approved",value:new Jr.q5}})}}),sn=(e,t)=>new qr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Jr.w$({result:{case:"rejected",value:new Jr.rA({reason:t??""})}})}}),an=(e,t)=>new qr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Gr.gz({result:t})}}),cn=(e,t)=>new qr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),ln=(e,t)=>new qr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),un=(e,t)=>new qr.Y5({id:e,result:{case:"prManagementResult",value:t}}),dn=(e,t)=>new qr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Kr.h({result:{case:"rejected",value:new Kr.OI({reason:t??"Authentication was rejected"})}})}}),hn=(e,t)=>new qr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new zr.qG({result:{case:"rejected",value:new zr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),pn=(e,t)=>new qr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Vr.vW({result:{case:"approved",value:new Vr.l3({description:t??""})}})}}),fn=(e,t)=>new qr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Vr.vW({result:{case:"rejected",value:new Vr.Uq({reason:t??""})}})}});var mn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),gn=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,ye.cF)(Symbol("pendingSubagentReplay"),void 0);class wn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const yn=X("subagent-executor",(e=>new K(e,ne("subagentArgs"),oe("subagentResult"))),((e,t)=>{t.register(new U(e,ie("subagentArgs"),se("subagentResult")))})),vn=X("subagent-await-executor",(e=>new K(e,ne("subagentAwaitArgs"),oe("subagentAwaitResult"))),((e,t)=>{t.register(new U(e,ie("subagentAwaitArgs"),se("subagentAwaitResult")))})),bn=X("force-background-subagent-executor",(e=>new K(e,ne("forceBackgroundSubagentArgs"),oe("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new U(e,ie("forceBackgroundSubagentArgs"),se("forceBackgroundSubagentResult")))}));class Sn{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 kn(e){return"string"==typeof e&&e.trim().length>0}const _n=X("web-fetch-allowlist-precheck-executor",(e=>new K(e,ne("webFetchAllowlistPrecheckArgs"),oe("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new U(e,ie("webFetchAllowlistPrecheckArgs"),se("webFetchAllowlistPrecheckResult")))})),Cn=e=>e.replace(/[\r\n]/g,"");function En(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":Cn(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":Cn(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":Cn(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const xn="x-inference-authentication-jwt";function Pn(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[xn]:t}}const In={textDelta:(e,t)=>new qr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new qr.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new qr.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new qr.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new qr.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new qr.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new qr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new qr.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new qr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new qr.tr3({thinkingDurationMs:e})}}),thinkingNote:e=>new qr.Uq({message:{case:"thinkingNote",value:new qr.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:In.toolCallDelta(e,new qr.V1v({delta:{case:"taskToolCallDelta",value:new qr.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new qr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new qr.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new qr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new qr.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new qr.Uq({message:{case:"tokenDelta",value:new qr.Fyz({tokens:e})}}),summary:e=>new qr.Uq({message:{case:"summary",value:new qr.ECk({summary:e})}}),summaryStarted:()=>new qr.Uq({message:{case:"summaryStarted",value:new qr.lWT}}),heartbeat:()=>new qr.Uq({message:{case:"heartbeat",value:new qr.ih1}}),summaryCompleted:(e,t,r)=>new qr.Uq({message:{case:"summaryCompleted",value:new qr.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new qr.Uq({message:{case:"shellOutputDelta",value:new qr.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new qr.Uq({message:{case:"modelCallCompleted",value:new qr.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 qr.Uq({message:{case:"turnEnded",value:new qr.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 qr.QVp({rawCostCents:r,chargedCents:r,source:qr.nnk.CATALOG})}:{}})}})},stepStarted:e=>new qr.Uq({message:{case:"stepStarted",value:new qr.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new qr.Uq({message:{case:"toolRequestsListed",value:new qr.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new qr.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new qr.Uq({message:{case:"stepCompleted",value:new qr.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new qr.Uq({message:{case:"activeBranchChange",value:new qr.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new qr.Uq({message:{case:"feedbackRequest",value:new qr.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class Rn{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 Tn=r("../agent-kv/dist/index.js");function An(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 $n=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),Mn=r("../utils/dist/fresh-uuid.js"),Dn=r("@connectrpc/connect"),On=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),Fn=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Nn=r("zod/v4");const jn="relayedAttemptFailure",Ln=Nn.object({transport:Nn.boolean(),stallAborted:Nn.boolean(),errorName:Nn.string(),connectCode:Nn.number().optional(),connectCodeName:Nn.string().optional(),connectCause:Nn.object({code:Nn.union([Nn.string(),Nn.number()]).optional(),name:Nn.string().optional()}).optional(),transportFailureKind:Nn.string().optional(),loop:Nn.string().optional(),transportMode:Nn.string().optional()});function Un(e){const t=e?.details?.additionalInfo[jn];if(void 0!==t)try{const e=Ln.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class Bn 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 Wn extends Bn{get kind(){return"RetriableError"}}class Hn extends Bn{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class qn extends Bn{get kind(){return"NonRetriableError"}}class zn extends qn{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 Gn extends Bn{get kind(){return"CancelledError"}}const Vn=new Set([Fn.yM.NOT_LOGGED_IN,Fn.yM.AGENT_REQUIRES_LOGIN,Fn.yM.AUTH_TOKEN_NOT_FOUND,Fn.yM.AUTH_TOKEN_EXPIRED,Fn.yM.INVALID_AUTH_ID,Fn.yM.UNAUTHORIZED,Fn.yM.GITHUB_NO_USER_CREDENTIALS,Fn.yM.GITHUB_USER_NO_ACCESS]),Kn=new Set([Fn.yM.FREE_USER_USAGE_LIMIT,Fn.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Fn.yM.PRO_USER_ONLY,Fn.yM.PRO_USER_USAGE_LIMIT,Fn.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Fn.yM.RATE_LIMITED,Fn.yM.RATE_LIMITED_CHANGEABLE,Fn.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Jn=new Set([Fn.yM.USAGE_PRICING_REQUIRED,Fn.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Zn=new Set([Fn.yM.BAD_API_KEY,Fn.yM.BAD_USER_API_KEY,Fn.yM.OUTDATED_CLIENT]),Xn=new Set([Fn.yM.USER_ABORTED_REQUEST,Fn.yM.DEBOUNCED]),Qn=new Set([Fn.yM.CUSTOM_MESSAGE]),Yn=new Map([[Dn.Code.PermissionDenied,"Permission Denied"]]),eo=["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"],to=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ro=new RegExp(`\\b(${[...to].join("|")})\\b`),no=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],oo="x-cursor-inference-request-error-type",so="AgentWebSocketDeliveryAmbiguousError";function io(e,t={}){const{requestId:r}=t;if(e instanceof Bn)return e;if(ao(e))return function(e,t){const r=lo(e),n=r.code,o=uo(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[jn])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[jn],t.details.equals(new Fn.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:ho(r,oo)??ho(e,oo),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===Un(o)?.transport?{isTransport:!0}:{}};if(n===Dn.Code.Canceled||n===Dn.Code.Aborted)return vo(e)?new Wn(e.message,a):new Gn(e.message,a);if(void 0!==s?.error){const t=s.error;if(Xn.has(t))return new Gn(go(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Hn(go(e,s),r,a);if(void 0!==Po(s))return new Wn(go(e,s),a);if(Vn.has(t))return new Hn(go(e,s),"login",a);if(Kn.has(t))return new Hn(go(e,s),"upgrade",a);if(Jn.has(t))return new Hn(go(e,s),"payment",a);if(Zn.has(t))return new Hn(go(e,s),"config",a);if(Qn.has(t)&&!0!==s.details?.isRetryable)return new qn(go(e,s),a);if(!1===s.details?.isRetryable)return new qn(go(e,s),a)}if(n===Dn.Code.Unauthenticated)return new Hn(e.message,"login",{...a,displayInfo:co(i,"Sign in required",r)});const c=Yn.get(n);return void 0===c||!0===s?.details?.isRetryable||vo(e)?new Wn(e.message,a):new qn(go(e,s),{...a,displayInfo:co(i,c,r)})}(e,r);const n=(0,Tn.y_)(e);if(void 0!==n)return new qn(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===wo)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new qn(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 qn(yo,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:yo,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Gn(e.message,{cause:e,requestId:r});if(e.name===so)return new Wn(e.message,{cause:e,requestId:r,isTransport:!0});if(vo(e))return new Wn(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Wn(s,{cause:e instanceof Error?e:void 0,requestId:r})}function ao(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 co(e,t,r){return{...e,title:e.title||t,detail:e.detail||mo(r),isRetryable:e.isRetryable??!1}}function lo(e){let t=e;for(let e=0;e<10&&t.code===Dn.Code.Unknown;e++){const e=t.cause;if(!ao(e))break;t=e}return t}function uo(e){let t=e;for(let e=0;e<10&&ao(t);e++){try{const e=t.findDetails?.(Fn.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function ho(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 po(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(ao(t))return t;t="cause"in t?t.cause:void 0}}function fo(e){const t=po(e);return void 0===t?void 0:lo(t)}function mo(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function go(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 wo="SummaryPlaceholderRejectedError",yo="Out of disk space. Free some space and try again.";function vo(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(eo.some((t=>e.includes(t)))||ro.test(e))return!0;const n=r.code;if("string"==typeof n&&(eo.some((e=>n.includes(e)))||to.has(n)))return!0;r=r.cause}return!1}function bo(e){return eo.some((t=>e.includes(t)))||ro.test(e)}function So(e){return e instanceof Bn&&e.cause instanceof Error?vo(e.cause):e instanceof Error?vo(e):"string"==typeof e&&bo(e)}function ko(e){return void 0!==e&&e>0}function _o(e){return e+1}function Co(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Eo(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return ko(n)?Co(new Wn("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${_o(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Co(new Wn("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}function xo(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(ao(t)&&(t.code===Dn.Code.Canceled||t.code===Dn.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Po(e){const t=e?.details?.additionalInfo;if(e?.error!==Fn.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 Io=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},Ro=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 To extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ao{constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Io(t,(0,i.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,sr.isMessage)(t,x.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const n=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,i.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,i.fU)(n)}else n=e;Io(r,o?new i.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{Ro(r)}})();r.push(n)}await Promise.all(r)}catch(e){if(e instanceof Dn.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new To(e.message);if(e instanceof Dn.ConnectError&&e.code===Dn.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 To(e.message)}else{if(e instanceof P.W2)throw new To(e.message);if(e instanceof Dn.ConnectError&&e.code===Dn.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new To(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ro(t)}}}var $o=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Mo=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Do=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),Oo=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class Fo extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Fo.telemetryName="InteractionListenerStreamClosedError";var No=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 jo=(0,C.h)("ClientInteractionController"),Lo=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Uo{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,i.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=>{jo.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{No(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Lo.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 en(e.id,t);case"webFetchRequestQuery":return rn(e.id,t);case"askQuestionInteractionQuery":return nn(e.id,new $o.tz({result:{case:"rejected",value:new $o.ox({reason:t})}}));case"switchModeRequestQuery":return sn(e.id,t);case"createPlanRequestQuery":return an(e.id,new Gr.bK({result:{case:"error",value:new Gr.iY({error:t})}}));case"setupVmEnvironmentArgs":return cn(e.id,new Oo.r$({result:{case:"success",value:new Oo.JH({})}}));case"replaceEnvArgs":return ln(e.id,new Do.dV({result:{case:"failure",value:new Do.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return un(e.id,new Mo.HL({result:{case:"error",value:new Mo.K$({error:t})}}));case"mcpAuthRequestQuery":return dn(e.id,t);case"connectScmRequestQuery":return hn(e.id,t);case"generateImageRequestQuery":return fn(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 qr.Y5))throw r;return jo.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=>{jo.error(e,"Error handling interaction query",t)})).finally(o)}}async function Bo(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Gn("User aborted request");throw new qn("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new qn("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new qn("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new qr.Ibo({bearerToken:r.bearerToken})}const Wo=15728640,Ho=(0,E.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),qo=(0,E.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),zo=(0,E.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Go(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Vo{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,Tn.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,Tn.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Tn.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Tn.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,Tn.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 Ko({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Go(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(Fr),o=await n.execute(e,new Nr._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),Wo),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 Nr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Nr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Nr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Nr.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,Tn.Bk)(i),(0,Tn.Bk)(a),(0,Tn.Bk)(c),(0,Tn.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Nr.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,Ho.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,Ho.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 Ho.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),qo.histogram(e,m,{mode:o}),zo.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 Jo(e){return Object.keys(e.fileContents).length>0}function Zo(e,t){return Object.assign(new(e.getType()),e,t)}function Xo(e){return Zo(e,{fileContents:{}})}function Qo(e){for(const[t]of e.entries())if(t.symbol===Fr.symbol)return e.get(Fr)}class Yo{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function es(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!==m.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=S(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)=>_.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(S);if(!i.some((e=>k(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&&!!(w(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>k(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 Nr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ts(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function rs(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ts(r)&&ts(n)&&ts(o)&&ts(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,...ts(i)?{dynamicBytes:i}:{}}}const ns=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],os=/\bHTTP (\d{3})\b/;function ss(e){const t=e.message;return"string"==typeof t?t:""}function is(e){return e instanceof Error&&("AbortError"===e.name||e.name===so)}const as={serverCap:3,transportCap:10},cs={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 ls(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function us(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 Bn?e:io(e,{requestId:n});const c=a instanceof Gn&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Xn.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Gn||a instanceof Wn),u="owner"===r.abortOrigin&&a instanceof Wn&&xo(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(ss),o=e=>n.some((t=>t.includes(e))),s=function(e){return fo(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===Dn.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===Dn.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>os.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===Dn.Code.Unknown&&"464"===a?"http_464":i&&s===Dn.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===Dn.Code.DeadlineExceeded&&function(e){const t=po(e);return void 0===t?void 0:uo(t)?.error}(e)===Fn.yM.TIMEOUT?"idle_deadline":i&&s===Dn.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":So(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(is)?"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(Eo(f()),{countAsTransportError:!0});const e=p((()=>Eo(f())),(()=>Eo({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Gn&&!c&&xo(a)&&(a=new Wn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Gn(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Hn||a instanceof qn)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!no.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):ls(d);if(a instanceof Gn||a instanceof Hn||a instanceof qn)return h(a);const m=function(e){return Po(e.displayInfo?.errorDetails)}(a);if(a instanceof Wn&&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}}return a instanceof Wn&&(!0===a.isTransport||function(e,t){const r=cs[e];return"by_signature"===r?So(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&xo(a))?p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return ko(n)?new Wn("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${_o(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}}):new Wn("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:"The connection was interrupted. Please check your network connection and try again.",isRetryable:!0,connectCode:o}})}(f())),(()=>a),{immediateFirstRetry:!0}):s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Wn(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${_o(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):ls(d):h(a)}var ds=r("../proto/dist/generated/agent/v1/mcp_pb.js");const hs=(0,C.h)("@anysphere/agent-client:stall-detector"),ps=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,fs={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},ms=(0,E.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),gs=(0,E.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),ws=(0,E.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),ys=(0,E.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class vs{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 bs{constructor(e,t,r){this.lastActivityTime=Date.now(),this.lastMeaningfulActivityTime=Date.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.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.logPrefix=fs[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),ys.increment(this.ctx,1,{loop:this.loop}),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}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=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.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=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=Date.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()}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{if(this.paused)return void(this.timer=setTimeout(e,this.thresholdMs));const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{if(this.paused)return void(this.advisoryTimer=setTimeout(t,e));const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{if(this.paused)return void(this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs));const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(As),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName),this.abortedAt&&(r.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(r.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(r.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const n=[];let o;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:s}=this.activityHistory[e];o!==t&&(o?n.push(`[${t}]`):n.push(`[${t}] (MOST RECENT)`),o=t),n.push(`${r}${s?` (x${s})`:""}`)}return r.activities=n.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=Date.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=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(As);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(hs.warn(this.ctx,a,i),ms.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",loop:this.loop}),this.hasEverStalled||(this.hasEverStalled=!0,ws.increment(this.ctx,1,{loop:this.loop})),this.onStallCallback){const t=Date.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:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs: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?.()}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});hs.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=Date.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),gs.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",loop:this.loop})}[Symbol.dispose](){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=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Ss=(0,ye.cF)(Symbol("agentTransportTimingRecorder"),void 0),ks=(0,C.h)("@anysphere/agent-client:turn-runner"),_s=1e3,Cs=6e4;async function Es(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Gn("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 Gn("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function xs(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 Ps(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Is(e){e=s2codeRetryGuard.guard(e);const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let c=_s;const l=async(r,o,s,i,a)=>{if(s||(c=_s),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&&ks.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Es(n,o)}const l=s?function(e,t){const r=Math.min(3e5,3*e);return t??_s+(r-_s)*Math.random()}(c,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:_s,o=r??Math.min(n*2**e,Cs);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,Cs),n=Math.min(r+.2*r*Math.random(),Cs);return Math.max(e,n)}(l,i.retryAfterMs);u!==l&&e.logging&&ks.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:l,selectedDelayMs:u,endlessRetries:s}),s&&(c=l,e.logging&&ks.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 Es(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let u,d,h,p,f,m=e.state,g=e.action,w=0,y=o,v=0,b=0,S=!1,k=0;const _=()=>{S&&(n.onConnectionStateChange?.({state:"connected"}),S=!1)},C=e=>()=>{e===w&&(f=!0,_())},E=e=>({handleCheckpoint:async(t,n,o)=>{e===w&&(f=!0),await r.handleCheckpoint(t,n,o),e===w&&(u=n,d=o?.resumeEligibility??"eligible",_())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,y);if(u=void 0,d=void 0,f=!1,s.beginAttempt?.({attempt:w,originalRequestId:a}),w>0?(y=(0,Mn.C)(),await(n.onRetryStarting?.(w,{actionCase:g.action.case,conversationState:m,isResume:"resumeAction"===g.action.case,attemptRequestId:y})),e.logging&&ks.info(t,`[${e.logging.tag}] Retrying attempt ${w}`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}),"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&ks.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))):(e.logging&&ks.info(t,`[${e.logging.tag}] Initial request`,{attempt:w,actionCase:g.action.case,requestId:y}),!0===e.notifyInitialResume&&"resumeAction"===g.action.case&&(await(n.onRetryResuming?.({checkpointState:m,nextAttempt:w,reason:"resume_action"})),e.logging&&ks.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:w,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,y);try{return await s.runAttempt({state:m,action:g,checkpointHandler:E(w),attempt:w,attemptRequestId:y,notifyConnected:_,notifyApplicationProgress:C(w)}),_(),void(e.logging&&ks.info(t,`[${e.logging.tag}] Request successful`,{attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,y);const o=!0===n.endlessRetries?.(),_=e.nowMs?.()??Date.now();f&&(h=void 0,p=void 0);const C=void 0===h?void 0:_-h,E=void 0===p?void 0:_-p;let I=s.classify(r,{attempt:w,attemptRequestId:y,originalRequestId:a,serverErrorRetries:v,transportErrorRetries:b,stallRetryElapsedMs:C,rateLimitRetryElapsedMs:E,endlessRetries:o});if("retry"===I.action){const n="resumeAction"===g.action.case||!0===e.noProgressGuardCountsReplays&&w>0;void 0!==u?k=0:n&&f&&(k++,k>=2&&(e.logging&&ks.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:k,attempt:w,requestId:y,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),I={action:"throw",error:new Wn("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:y,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:I.transportFailureKind}))}const R={...void 0===I.transportFailureKind?{}:{transportFailureKind:I.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},T=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===I.action?`RETRY (countAsServerError=${I.countAsServerError}, countAsTransportError=${I.countAsTransportError})`:`THROW ${I.error.kind}`;ks.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${y} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===I.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:v,transportErrorRetries:b,attempt:w,requestId:y,originalRequestId:a,...R,...T})}if("throw"===I.action){if(0===w){const r={attempt:0,actionCase:g.action.case,error:I.error,requestId:y,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&ks.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:y,originalRequestId:a})}}throw e.logging&&ks.warn(t,`[${e.logging.tag}] Error not retryable`,{...R,...T,attempt:w,actionCase:g.action.case,requestId:y,originalRequestId:a,errorName:I.error.name,...!0===e.logging.includeErrorObjects?{error:I.error}:{},serverErrorRetries:v,transportErrorRetries:b}),I.error}const A=w+1;if("ineligible_terminal_turn"===d)return void(e.logging&&ks.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!==I.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:A,trigger:{...R,...s.reconnectTrigger?.(r,I,{originalRequestId:a,failedAttemptRequestId:y,nextAttempt:A})??{originatingRequestId:a,attemptRequestId:y}}}),S=!0),I.countAsServerError&&v++,I.countAsTransportError&&b++,!0===I.stall?h??=_:h=void 0,!0===I.rateLimit?p??=_:p=void 0,w=A,void 0!==u&&(P=u,xs((x=m).turns,P.turns)&&xs(x.rootPromptMessagesJson,P.rootPromptMessagesJson)||(c=_s),m=u,g=new qr.QFf({action:{case:"resumeAction",value:new qr.qKo}})),s.onRetryCommitted?.(),!0===I.immediate||!0===I.noBackoff&&void 0===I.retryAfterMs||await l(w,t.signal,o,I,r)}}var x,P}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var Rs=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},Ts=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 As=(0,ye.cF)(Symbol("agentStreamMetadata"),void 0),$s=(0,C.h)("@anysphere/agent-client:abort"),Ms=(0,C.h)("@anysphere/agent-client:retry"),Ds=(0,C.h)("@anysphere/agent-client:request-context-blob");async function Os({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Go(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Jo(r)&&(t.requestContext=Xo(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Jo(o)&&(e.requestContextParts=Zo(n,{dynamicContext:Xo(o)}))}(t);try{const s=await Ko({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Wo,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?rs(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?rs(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ds.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 Fs=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 Ns(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 js(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,In.shellOutputDelta({case:"stdout",value:new xr.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,In.shellOutputDelta({case:"stderr",value:new xr.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,In.shellOutputDelta({case:"exit",value:new xr.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Ls(e){return e instanceof Error?e.name:void 0}class Us{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,a,c,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new zn(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Qo(e);return void 0===t?e:new re(e,[Y(Fr,{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&&Jo(r)?new Nr._G({result:{case:"success",value:Zo(t,{requestContext:Xo(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new Yo:void 0,y=void 0===w?g:function(e,t){const r=Qo(e);return void 0===r?e:new re(e,[Y(Fr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?es(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Vo(a),S=d.generationUUID??(0,Mn.C)(),k=new Rn,_=(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=po(e);return void 0===t?void 0:Un(uo(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:Ls(e)},r=fo(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=Ls(n);return{...t,underlyingConnectError:{code:r.code,codeName:Dn.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 I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Ms.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=Rs(h,(0,i.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,i.MG)(R.span,(()=>Is({interaction:_,checkpointError:(cause,requestId,message)=>new qn(message,{cause,requestId,displayInfo:{title:"Cursor conversation was not saved",detail:message,isRetryable:!1}}),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,...Ps(n)}}},cancellation:{toCancelledError:()=>new Gn("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:a,notifyApplicationProgress:l})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Ms.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Gn("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,d,y,b,c,o,u,v,i,S,k,C,a,l,s,I)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=us(e,function(e,t,r=as){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)&&ns.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 Bn?e:io(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:()=>c.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Ts(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,l,u,d,h,p,f,m,g,w,y,v,b,S="agent.request.attempt"){const k={stack:[],error:void 0,hasError:!1};try{const E=e;e=this.options.prepareAttemptContext?.(e,{attempt:v,attemptRequestId:p,originalRequestId:f,runOptions:h})??e;const I=Rs(k,(0,i.VI)(e.withName(S)),!1);I.span.setAttribute("agent.attempt",v),I.span.setAttribute("agent.request_id",p),I.span.setAttribute("agent.original_request_id",f),e=I.ctx,e=(0,i.Mf)(e,"agent.request_id",p),e=(e=(0,i.Mf)(e,"agent.original_request_id",f)).with(As,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:n});const R=new Set(g.sources);let T=void 0!==g.abortReasonName||void 0!==g.abortReasonMessage;const A=(t,r)=>{if(R.has(t))return;R.add(t),g.sources=[...R];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,g.abortReasonName=n.abortReasonName,g.abortReasonMessage=n.abortReasonMessage),$s.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:p,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",An(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",An(t))}),{once:!0});const[$,M]=e.withCancel();if(l.signal?.aborted){const e=l.signal?.reason;A("conversation_action_abort",An(e)),M()}else l.signal?.addEventListener("abort",(()=>{const e=l.signal?.reason;A("conversation_action_abort",An(e)),M()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Gn("User aborted request")}const D=(0,i.VI)(e.withName("createControlledExecManager")),O=W.fromResources(s);D[Symbol.dispose]();const[F,N]=e.withCancel(),j=new vs,{failThresholdMs:L,advisoryThresholdMs:U}=function(e,t){const r=ps(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=ps(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o{A("stall_detector",{thresholdMs:L,advisoryThresholdMs:U}),N()},onStallCallback:h.onStall,handlerTracker:j}),!1);let H,q;const z=(0,On.Jt)(),G=new P.F8(z,(e=>(B.reset("outbound_write",Fs(e)),e))),V=Rs(k,(0,i.VI)(e.withName("writeInitialRequest")),!1);let K;const J=function(e){return new ds.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?sr.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(d),Z=h.requestContextBlobTransportMode??"legacy",X=0===v&&"userMessageAction"===r.action.case&&0===t.turns.length,Q="ref_only"===Z&&X?"dual":Z,[,Y]=await Promise.all([Os({ctx:e,action:r,resources:s,blobStore:a,options:h,source:"run_request",transportMode:Q,notifyBytes:0===v}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):Bo(h.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:p})]),ee={action:r,headers:h.headers??{}},te=this.options.decorateAttempt?.(ee,h)??ee,re=new qr.Mpn({conversationState:t,action:te.action,modelDetails:n,requestedModel:h.requestedModel,clientLlmGatewayCredential:Y,mcpTools:J,conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:h.subagentModelOverrides??[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,firstProjectOnboarding:h.firstProjectOnboarding,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,emitModelCallUsage:h.emitModelCallUsage,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,transcriptParentConversationId:h.transcriptParentConversationId,runId:f,nextInteractionQueryId:m.peekNext(),voiceCallNotes:h.voiceCallNotes});if(K=G.write(new $n.KS({message:{case:"runRequest",value:re}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),V[Symbol.dispose](),new Gn("User aborted request")}const ne={...te.headers,"x-request-id":p,"x-original-request-id":f,...En(h),...Pn()};H=(0,i.VI)(e.withName("handshakeEstablishment")),H.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=function(e){return e?.get(Ss)}(e)?.startTransportRun(),se=void 0===oe?H.ctx:function(e,t){return e.with(Ss,t)}(H.ctx,oe),ie=0===v&&void 0!==h.onTtftBreakdown?b?.networkPhaseStartedAt:void 0;let ae;const ce=void 0===oe&&void 0===ie?z:(_=z,C=()=>{ae=performance.now(),oe?.markFirstRequestSent(ae)},{[Symbol.asyncIterator](){const e=_[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,C()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),le=this.client.run(se,ce,{signal:F.signal,headers:ne,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===q&&(q=performance.now())}}),ue=performance.now();let de;const he=e=>{H&&(H.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==q&&H.span.setAttribute("handshake.preNetworkMs",q-ue),H[Symbol.dispose](),H=void 0),w();const t=performance.now();de=t,h.onFirstMessage?.(t-ue),void 0!==q&&h.onFirstMessageNetwork?.(t-q)},pe=()=>{y(),h.onFirstNonHeartbeatResponse?.(performance.now()-ue,v)},fe=h.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ie||void 0===ae||"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:ie,transportRunCalledAt:ue,firstRequestTakenAt:ae,firstMessageAt:de??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});h.onTtftBreakdown(void 0===r?e:{...e,transit:r},v)}:void 0,{interactionStream:me,execStream:ge,checkpointStream:we,kvStream:ye,done:ve}=function(e,t,r,n,o,s,i,a){const c=(0,On.Jt)(),l=(0,On.Jt)(),u=(0,On.Jt)(),d=(0,On.Jt)();let h=!1,p=!1;return{interactionStream:c,execStream:l,checkpointStream:u,kvStream:d,done:async function(){let f,m,g=!1,w=!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.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Ms.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(h||(h=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{i?.()}catch(t){Ms.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",Fs(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(g=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await c.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await l.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:o.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===o.message.case&&await d.write(o.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof Bn?e:io(e);return t instanceof Wn&&function(e){return!0===e.isTransport||(e.cause instanceof Error?vo(e.cause):bo(e.message))}(t)}(f)&&(Ms.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)}),r.onStreamEnded(),m=void 0),g||o?.aborted||s?.aborted){if(!g&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${h}`;Ms.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(Ms.warn(e,t),m=new Wn(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(Ms.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new Wn(t,{cause:f,isTransport:!0})):Ms.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Ns(f)})}c.close(),l.close(),u.close(),d.close()}if(void 0!==m)throw m}()}}(e,le,B,he,$.signal,e.signal,pe,fe);let be;const Se={handleCheckpoint:async(e,t,r)=>{await u.handleCheckpoint(e,t,r),be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>u.getLatestCheckpoint()};V[Symbol.dispose]();const ke=5e3;let _e;const Ce=()=>{_e=setTimeout((()=>{G.write(new $n.KS({message:{case:"clientHeartbeat",value:new $n.kA}})).then((()=>B.onClientSentHeartbeat()),(()=>{})),Ce()}),ke)},Ee=()=>{void 0!==_e&&(clearTimeout(_e),_e=void 0)};Ce();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new xr.a({command:n.shellCommand?.command||"",parsingResult:new xr.HO,skipApproval:!0}),a=s.get(Rr).execute(e,i,{execId:n.execId}),c=new Uo(me,o,new P.F8(G,(e=>new $n.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async e=>{await Promise.all([j.track("handleShellStream",js(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Uo(me,o,new P.F8(G,(e=>new $n.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==K&&await Promise.race([K,ve.catch((()=>{}))]);const i=new P.F8(G,(e=>{if((0,sr.isMessage)(e,x.yT))return new $n.KS({message:{case:"execClientMessage",value:e}});if((0,sr.isMessage)(e,x.$Y))return new $n.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,sr.isMessage)(e)?e.getType().typeName:typeof e})`)})),u=new Ao(ge,i,O),v=new Tn.hC(ye,new P.F8(G,(e=>new $n.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),b=new c(we,Se,e);let S,k;const _={promise:new Promise(((e,t)=>{S=e,k=t})),resolve:S,reject:k};$.canceled?(_.resolve(),me.close()):$.signal.addEventListener("abort",(()=>{_.resolve(),me.close()}),{once:!0}),u.run($).then(_.resolve).catch(_.reject);const C=Promise.allSettled([j.track("streamSplitter",ve.finally((()=>{Ee(),l.close(),i.close()}))),j.track("execHandler",_.promise),t.run(e),j.track("checkpointController",b.run()),j.track("kvHandler",v.run(e)),j.track("conversationActionManager",l.run(e,{write:async t=>{await Os({ctx:e,action:t,resources:s,blobStore:a,options:h,source:"queued_action"}),await G.write(new $n.KS({message:{case:"conversationAction",value:t}}))}}))]);let I,R;const T={promise:new Promise(((e,t)=>{I=e,R=t})),resolve:I,reject:R};C.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Gn("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Gn("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?N():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:ve,lingerMs:h.softCancelLingerMs}).then((t=>{Ms.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:p}),N()}))};$.canceled?(A(),T.reject(new Gn("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Gn("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],F=M[1],L=M[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new qn("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===be;if(W){const t={..."rejected"===D.status?{streamSplitter:U(D)}:{},..."rejected"===F.status?{execHandler:U(F)}:{}};Object.keys(t).length>0&&Ms.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!W)throw D.reason;if("rejected"===F.status&&!W)throw F.reason;$.canceled||await this.processUnprocessedMessages(E,l,Se,n,o,s,a,d,h,p,f,m,g,B,w,y)}finally{Ee(),H&&(H[Symbol.dispose](),H=void 0)}}catch(e){k.error=e,k.hasError=!0}finally{Ts(k)}var _,C}async processUnprocessedMessages(e,t,r,n,o,s,i,a,c,l,u,d,h,p,f,m){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),w=r.getLatestCheckpoint();if(!w||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const v=r.getLatestCheckpoint();try{await this.runInternal(e,w,new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:y})}}),n,o,s,i,t,r,a,c,l,u,d,h,f,m,0,void 0,"agent.request.queuedMessage")}catch(e){throw v===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}new RegExp([String.raw`"type"\s*:\s*"response\.(?:output_text|reasoning_summary_text|reasoning_text|function_call_arguments|refusal)\.(?:delta|done)"`,String.raw`"(?:content|reasoning_content|reasoning|refusal)"\s*:\s*"(?!")`,String.raw`"tool_calls"\s*:\s*\[\s*\{`,String.raw`"type"\s*:\s*"content_block_delta"`].join("|"));var Bs=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Ws=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const Hs=(0,Dn.createContextKey)(void 0,{description:"anysphere.callerContext"});function qs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function zs(e){return e instanceof Error?e:new Error(String(e))}function Gs(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(zs(e)),t?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:Bs.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 Vs(...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 Ks(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:(a,c,l={})=>{const u=(0,i.fR)(a.withName(`rpc.${String(o)}`),{kind:Ws.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),d=(0,i.fU)(u);let h;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,i.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}(u)),n){const e=n(u);e&&(o=Vs(o,e))}const a=Vs(l.headers,o),{signal:f,cleanup:m}=!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)}}}(u.signal,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,Dn.createContextValues)()).set(Hs,u),w={...l,headers:a,signal:f,contextValues:g},y=s.call(e,c,w);return qs(y)?Gs(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?Promise.resolve(y).then((e=>qs(e)?Gs(e,d,h):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(zs(e)),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:Bs.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(zs(e)),d?.setStatus({code:Bs.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Js=r("node:crypto?8af2"),Zs=r("../utils/dist/workspace-paths.js");function Xs(){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 Qs(e){return(0,s.join)(Xs(),(0,Zs.r_)(e))}var Ys=r("node:fs/promises"),ei=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),ti=r("node:fs"),ri=r("../shell-exec/dist/api/index.js"),ni=r("./src/agent/native/tree-sitter.webpack.cjs"),oi=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const si=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(oi),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 ni)),ii=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),ai=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function ci(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=>ai.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)ii.has(r.type)&&h(r,t)})(t),ii.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 li(e){return ci(si(),e)}function ui(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function di(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function hi(e,t){const r=di(e,t);return ui(e,r)?r-1:r}function pi(e,t){const r=di(e,t);return ui(e,r)?r+1:r}function fi(e,t){return t>0?e.length<=t?e:e.slice(0,hi(e,t)):""}function mi(e,t){return t>0?e.length<=t?e:e.slice(pi(e,e.length-Math.trunc(t))):""}let gi,wi;function yi(e,t){gi??=new TextEncoder,wi??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,bi.o1)(e);try{return await(0,Ys.realpath)(t)}catch{return t}},_i=1048576,Ci=52428800;var Ei=r("../utils/dist/test-resets.js");const xi="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Pi="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Ii=/\$\(|`|<\(|>\(/,Ri=/[;&|]/;let Ti,Ai,$i,Mi;function Di(){if(void 0===Ti){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ti=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ti}function Oi(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 Fi(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ni(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 ji(){if(void 0===Mi){const e=(process.env[xi]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xi} (expected "allow" or "deny"); using "deny".`);const r=Fi("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Pi]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fi(Pi)),Mi={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fi("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ni("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Mi}function Li(e,t,r={}){const n=[Oi(e),Oi(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 Ui(e,t){const r=function(){const e=ji();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===Ai&&(Ai=Li("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Ai);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Ii.test(e))return r;const s=(void 0===$i&&($i=Li("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$i);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ri.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=ji();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,Ei.J)((function(){Ti=void 0,Ai=void 0,$i=void 0,Mi=void 0}));var Bi=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Wi(e){if(!e)return;let t;return"allow"===e.default?t=Bi.h1.ALLOW:"deny"===e.default&&(t=Bi.h1.DENY),new Bi.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Bi.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Hi(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 Bi.h1.ALLOW:t.default="allow";break;case Bi.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,ri.T6)():(0,ri.Po)())}function qi(e){switch(e){case"system":return Bi.Sz.SYSTEM;case"workspace":return Bi.Sz.WORKSPACE;default:return Bi.Sz.UNSPECIFIED}}function zi(e){const t=function(e){switch(e){case Bi.Sz.SYSTEM:return"system";case Bi.Sz.WORKSPACE:return"workspace";case Bi.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Gi(e){if(!e)return{type:"insecure_none"};switch(e.type){case Bi.vc.INSECURE_NONE:case Bi.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Bi.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Hi(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,...zi(e)};case Bi.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Hi(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...zi(e)};default:return{type:"insecure_none"}}}function Vi(e){if(e)return"insecure_none"===e.type?new Bi.Mw({type:Bi.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Bi.Mw({type:Bi.vc.WORKSPACE_READWRITE,networkAccess:(0,ri.$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:Wi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:qi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Bi.Mw({type:Bi.vc.WORKSPACE_READONLY,networkAccess:(0,ri.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Wi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:qi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Bi.Mw({type:Bi.vc.INSECURE_NONE})}function Ki(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function Ji(e){let t="",r=!1;for(const n of e)Ki(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function Zi(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ta={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ra(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ta[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 Ji(t)}function na({rule:e,command:t}){const r=Ji(e).trim();return 0!==r.length&&(null!==function(e){const t=Ji(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(Zi(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=Xi(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(Zi(e)&&(0===t.length||Zi(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Ji(t).trim(),ra(t).trim()].some((e=>function(e,t){const r=Xi(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(Yi(e,s)&&Yi(n,i))return!0}return e.includes("*")?Yi(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function oa({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=>na({rule:e,command:t}))))return e}function sa(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 ia({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=oa({matchForms:ea({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:sa(n)}var aa=r("../utils/dist/lru-cache.js");const ca=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],la="/Volumes";function ua(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function da(e,t){if("darwin"!==t.platform)return[];const r=ua(e),n=r.toLowerCase(),o=ua(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...ca.map((e=>`${o}/${e}`)),la].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var ha=r("node:util"),pa=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),fa=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function ma(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const ga="utf8",wa="utf8bom",ya="latin1",va={"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 ba(e){return va[e]||e}function Sa(e){return e.startsWith("\ufeff")?e.slice(1):e}function ka(e){const t=e.toLowerCase();return"latin-1"===t?ya:"utf-8"===t?ga:"utf-8-bom"===t||"utf-8 bom"===t?wa:t}function _a(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 Ca=new ha.TextDecoder("utf-8",{fatal:!1}),Ea=new ha.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),xa="�";function Pa(e){return Ca.decode(e)}function Ia(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function Ra(e){let t=0,r=e.indexOf(xa);for(;-1!==r;)t++,r=e.indexOf(xa,r+1);return t}function Ta(e,t){const r=e[t];let n,o=128,s=191;if(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 Aa(e){return e<128?1:e<2048?2:e<65536?3:4}var $a;!function(e){e.CRLF="CRLF",e.LF="LF"}($a||($a={}));const Ma=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Da=new Set(Ma),Oa=new ha.TextDecoder("utf-8",{fatal:!0}),Fa=new ha.TextDecoder("latin1"),Na=Buffer.from([239,187,191]),ja={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},La=8192,Ua="UTF-8",Ba="windows-1252",Wa=/[^\u0000-\u007f\ufffd]/u,Ha=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,qa=/(?:\p{Script=Greek}\p{M}*){3,}/gu,za=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ga=new Map([["windows-1251",Ha],["ISO-8859-5",Ha],["KOI8-R",Ha],["x-mac-cyrillic",Ha],["IBM866",Ha],["IBM855",Ha],["ISO-8859-7",qa],["windows-1253",qa],["windows-1255",za],["ISO-8859-8",za],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Va=/\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,Ka=/[\p{L}\p{M}]+/gu,Ja=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Za=new RegExp(`[A-Za-z]${Ja}{1,2}(?!${Ja})|^${Ja}{1,2}[A-Za-z]`,"u"),Xa=new Map,Qa=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Ma]),Ya=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i,ec=new Set([".ps1",".psm1",".psd1"]),tc=/[^\u0000-\u007f]/u;function rc(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function nc(e){const t=rc(e);return Da.has(t)}function oc(e){const t=rc(e);return{encoding:"binary",lineEnding:$a.LF,isBinaryFile:!0,isImageFile:Ya.test(t),isVideoFile:Da.has(t)}}async function sc(e,t){return(await ic(e,t)).text}async function ic(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Ys.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=uc(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=yc(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Sc(n,i),l=Sa(a),u=c===ga&&(d=n).length>=Na.length&&d[0]===Na[0]&&d[1]===Na[1]&&d[2]===Na[2]?wa:c;var d;return vc(e,r,u),o.lineEnding===$a.CRLF?{text:l.replaceAll("\r\n","\n"),encoding:u}:{text:l,encoding:u}}async function ac(e,t){if("binary"===t.encoding)return void wc(e);let r;try{r=await(0,Ys.stat)(e)}catch{return void wc(e)}r.size===t.buffer.byteLength?vc(e,r,t.encoding):wc(e)}async function cc(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await lc(e)}catch{}const r=rc(e);if(Qa.has(r))return oc(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of mc(e)){if(r>=100)break;try{const e=await lc(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:gc()}(t)}catch{return gc()}}(e,r):await lc(e)}catch{const t=rc(e);s=Qa.has(t)?oc(e):gc()}const a=()=>i??=async function(e){try{const t=await(0,Ys.stat)(e);if(!t.isFile()||t.size>Yt)return;return await(0,Ys.readFile)(e)}catch{return}}(e),c=yc(e,await async function(e){try{return await(0,Ys.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ka(o):c?r=ka(c):(r=ka(s.encoding),r!==ga&&r!==wa||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:bc(r).encoding===ya?ya:e}(r,a))),r===ga&&!o&&function(e,t){return"win32"===process.platform&&ec.has(rc(e))&&tc.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Ys.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=wa);const i=r===wa||r===ga&&!o&&await kc(e,Na),u=ja[ba(r)];i?l=Na:u&&await kc(e,u)&&(l=u),s={...s,encoding:i?wa:r}}const u=ma(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=Sa(Sc(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=_a(t),o=_a(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?Sa(t):t,p=s.encoding===wa?ga:s.encoding,f=p===ga?await async function(e,t){if(!t.includes(xa))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(xa)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Ea.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=Aa(o);continue}const s=Ta(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(xa);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:hc(pa.decode(e.subarray(0,La),ba(ka(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(La,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:Ua,lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=Pa(e),s=e.length,Ia(o)||1024*Ra(o)<=s&&!Wa.test(o)))return{encoding:Ua,lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=fa.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ga.get(a);return void 0!==c&&(a=function(e,t,r){const n=ba(ka(t));if(!pa.encodingExists(n))return t;const o=pa.decode(e,n);return Va.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of pa.decode(e,Ba).matchAll(Ka))Za.test(t)&&o++;return o>n}(e,o,r)?Ba:t}(e,a,c)),a!==Ba||function(e,t){const r=ba(ka(t));return!pa.getDecoder(r).write(e).includes(xa)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:dc(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function dc(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return pc(t,r)}function hc(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return pc(r,t-r)}function pc(e,t){return 0===e&&0===t?$a.LF:e/(e+t)*100>=5?$a.CRLF:$a.LF}async function fc(e){const t=await(0,Ys.open)(e,"r");try{const e=Buffer.allocUnsafe(La),{bytesRead:r}=await t.read(e,0,La,0);return e.subarray(0,r)}finally{await t.close()}}async function*mc(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,Ys.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*mc(r)):n.isFile()&&(yield r)}}catch(e){return}}function gc(){return{encoding:ga,lineEnding:"win32"===process.platform?$a.CRLF:$a.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function wc(e){Xa.delete(e)}function yc(e,t){const r=Xa.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Xa.delete(e)}function vc(e,t,r){if(Xa.has(e)&&Xa.delete(e),Xa.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Xa.size<=100)return;const n=Xa.keys().next().value;void 0!==n&&Xa.delete(n)}function bc(e){try{return{text:Oa.decode(e),encoding:ga}}catch{const t=Pa(e);return Ia(t)?{text:t,encoding:ga}:{text:Fa.decode(e),encoding:ya}}}function Sc(e,t){const r=ka(t);if(r===ga||r===wa||"ascii"===r){const t=bc(e);return r===wa&&t.encoding===ga?{text:t.text,encoding:wa}:t}if(r===ya)return{text:Fa.decode(e),encoding:ya};try{const t=ba(r);if(pa.encodingExists(t))return{text:pa.decode(e,t),encoding:r}}catch{}return bc(e)}async function kc(e,t){try{return(await fc(e)).subarray(0,t.length).equals(t)}catch{return!1}}var _c=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),Cc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class Ec{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Ec.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=uc(t);return r.isBinaryFile?Pa(t):Sa(Sc(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(Rc??=(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,ti.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),Rc),n=(0,s.join)(r,`cursorignore-${Tc(e)}-${Tc(t)}.txt`);if(await Ac(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Ys.writeFile)(i,t,"utf8"),await(0,Ys.rename)(i,n),n}(e,r)}(e,await(0,Ys.readFile)(e));return Pc.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function Mc(e){return Promise.all(e.map((e=>async function(e){const t=Ic.get(e);if(void 0!==t)return t;const r=$c(e).catch((()=>e)).finally((()=>{Ic.delete(e)}));return Ic.set(e,r),r}(e))))}(0,Ei.J)((function(){Pc.clear(),Ic.clear()}));var Dc=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 Oc(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 Fc(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 Mc(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,ri.spawnInSandbox)((0,ri.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=Oc(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 xc.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{Dc(r)}}(),didTimeout:w}}var Nc=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 jc;function Lc({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 Uc{constructor(e=()=>function(e=process.env){if(void 0!==jc)return jc;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}()){this.cache=new Ec({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(Lc(e))}walk(e,t){const r=Lc(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,Oc(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{Nc(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=Fc(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 Bc=[{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 Wc(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map(Bc.map((e=>[e.gitHost,e.apiHost]))),new Map(Bc.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Bc.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Bc.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Bc.map((e=>[e.apiHost,e.gitHost]))),new Map(Bc.map((e=>[e.apiHost,e.internalHost]))),new Map,function(e){const t=Bc.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t}("prod").gitHost;const Hc=new Map;function qc(e){if(void 0===e)return;if(Hc.has(e))return Hc.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||!Wc(t.hostname))return;const r=function(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}`:""}(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 Hc.size>=16384&&Hc.clear(),Hc.set(e,t),t}function zc(e){return void 0!==function(e){const t=qc(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 Gc=new WeakMap;function Vc(e,t,r){const n=performance.now();let o=Gc.get(t);void 0===o&&(o=new Map,Gc.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function Kc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Jc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Xc(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=Zc.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)??Xc(t)??t}}const Zc=new Set(["ftp","file","http","https","ws","wss"]);function Xc(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)}`))}function el(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function tl(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""}const rl=[".gitignore",".cursorignore"],nl=new Map,ol=new Map;function sl(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 il(e){const t=nl.get(e);return void 0!==t?t:sl(nl,2048,e,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())}async function al(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,bi.DN)(e);return null===t?null:t}async function cl(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}(0,Ei.J)((function(){nl.clear(),ol.clear()}));class ll{constructor(e,t,r){this.disposeRequested=!1,this.ignoreServicePromise=hl.init((0,ye.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ignoreServicePromise.then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise.then((e=>{e.dispose()})).catch((()=>{})))}}const ul=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class dl{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=_c().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class hl{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 aa.q({max:2e3}),this.cursorIgnoreCache=new aa.q({max:2e3}),this.gitRootCache=new aa.q({max:1e4}),this.gitRemoteUrlCache=new aa.q({max:200}),this.hasGitDirCache=new aa.q({max:1e3}),this.gitParsedIgnoreCache=new dl(1e4),this.cursorParsedIgnoreCache=new dl(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new aa.q({max:1e4}),this.unwalkedFolders=o.flatMap((e=>da(e,s)))}static getRipwalkCache(){return hl.ripwalkCache??=new Uc,hl.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,bi.DN)(e)??(0,bi.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,bi.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,or.PH)(r,(async e=>{const t=await(0,bi.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=>{const n=await Vc(e,t,r);return null!==n&&da(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([hl.initializeIgnoreMapping(u,".gitignore",c,i),hl.initializeIgnoreMapping(a,".cursorignore",l,i)]),new hl(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,bi.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 hl.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,Ys.access)(n,Ys.default.constants.F_OK);const t=await sc(n),o=hl.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===el(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=hl.deduplicateRootDirectories(e),i=await hl.promiseQueue.enqueueList(o,(e=>hl.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await sc(e),n=hl.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await hl.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,ye.q6)(),o=[],i={root:e,includeGlobs:rl.map((e=>`**/${e}`)),excludeGlobs:[...Qc,...Yc(e,r)],source:"ignore_scan"},a=hl.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}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=hl.parseIgnoreRules(await sc((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)=>_c().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,bi.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,bi.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,bi.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 hl.promiseQueue.enqueueList(o,(e=>hl.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,bi.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,bi.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,bi.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Ys.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const n=e[t];e[t]=n?[...n,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,bi.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()}dispose(){this.gitIgnoreCache=new aa.q({max:1}),this.cursorIgnoreCache=new aa.q({max:1}),this.gitRootCache=new aa.q({max:1}),this.gitRemoteUrlCache=new aa.q({max:1}),this.hasGitDirCache=new aa.q({max:1}),this.directoryWalkPlacementCache=new aa.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await sc(e),n=hl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await sc(e),n=hl.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,bi.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,Ys.access)((0,s.join)(e,".git"),Ys.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=await(this.teamSettingsService?.getTeamRepos());if(!t)return!1;const r=t.repos??[],n=t.disableLocalExecAllowlistEnforcement?[]:t.allowedRepos??[];if(0===r.length&&0===n.length)return!1;const o=await this.findGitRootsForFile(e);if(0===o.length)return this.checkNonRepoPathBlockedByAllowlist(e,n);let i=0===n.length,a=!1;for(const t of o){let o;if(this.gitRemoteUrlCache.has(t)?o=this.gitRemoteUrlCache.get(t):(o=await Kc((0,ye.q6)(),this.gitExecutor,t),void 0!==o&&this.gitRemoteUrlCache.set(t,o)),void 0===o)continue;const c=o,l=(0,s.relative)(t,e)||".";for(const e of r)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;n.length>0&&!a&&(a=!0,i=n.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,bi.ZU)({basePath:r,targetPath:e}))return!1;const n=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,n))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,n))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,bi.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,bi.oL)((0,s.relative)(t,e)):(0,bi.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,bi.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){return e.includes("*")?"*"===e.trim()||this.matchRepoUrlGlob(il(e),il(t)):il(e)===il(t)}matchGlob(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=ol.get(e);if(void 0!==t)return t;let r;try{const t=Cc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return sl(ol,2048,e,r)}(r)(t)}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),n=await this.getGitRepoMapping();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=>this.doesRepoUrlMatch(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(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],n=(0,ye.q6)();for(const e of this.rootDirectories){const o=(0,bi.o1)(e);try{await(0,Ys.access)((0,s.join)(o,".git"),Ys.default.constants.F_OK),t.includes(o)||t.push(o)}catch{}let i=(0,s.dirname)(o);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Ys.access)((0,s.join)(i,".git"),Ys.default.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:o,includeGlobs:["**/.git/config"],excludeGlobs:[...r,...Yc(o,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=hl.getRipwalkCache().walk(n,e);for await(const e of i.lines){const r=(0,s.join)(o,e),n=(0,s.dirname)(r),i=(0,s.dirname)(n);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Kc(n,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}hl.promiseQueue=new or.TJ({max:ul});const pl="agent-tools",fl=51380224;var ml=r("node:async_hooks");const gl=new ml.AsyncLocalStorage;function wl(e,t){return gl.run(e,t)}new ml.AsyncLocalStorage;var yl=r("../proto/dist/generated/agent/v1/utils_pb.js"),vl=r("../utils/dist/safe-spawn-cwd.js"),bl=r("node:child_process"),Sl=r("../utils/dist/workload-spawn.js");const kl=(0,C.h)("local-exec:shell-output-encoding"),_l=(0,ha.promisify)(bl.execFile),Cl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,El=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function xl(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const Pl="㐀-䶿一-鿿豈-﫿",Il=" -〿㈀-㏿︰-﹯＀-￯",Rl="‐-※←-⇿─-◿★☆",Tl="぀-ヿ",Al=new Map([["cp932",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${Pl}${Il}${Rl}${Tl}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${Pl}${Il}${Rl}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const $l=function(e){let t,r,n,o=!1,s=0;const i=()=>{s+=1;const e=s;n=async function(){const{stdout:e}=await(0,Sl.D9)(_l,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const s=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=xl(t,Cl),o=xl(t,El);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 pa.encodingExists(t)?t:void 0}(t);return void 0!==n&&Al.has(n)?n:void 0}(s),r=s,o=!0,n=void 0,kl.info((0,ye.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:s.oemcp??"none",acp:s.acp??"none"})}),(t=>{n=void 0,kl.warn((0,ye.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&&i(),{current:()=>("win32"===e&&!o&&void 0===n&&s<3&&i(),t),pages:()=>void 0!==r?r:"win32"!==e||s>=3&&void 0===n?"none":"pending",settled:()=>n??Promise.resolve()}}(process.platform),Ml=Buffer.alloc(0),Dl=/[\u0080-\uffff]/;function Ol(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 Fl(){const e=new xc.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Nl(e,t){return pa.decode(t,e,{stripBOM:!1})}const jl=/[\xe0-\xef][\x80-\xbf]\?/;const Ll=10,Ul=Buffer.alloc(0),Bl=new Set([7,8,9,10,11,12,13,27]);function Wl(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const zl={encoding:"utf8",skip:0};function Gl(e){const t=e();let r="utf8";const n={},o=()=>"utf8"===r?t:n[r]??=ql(r);let s,i=!0,a=Ul,c=!1,l=0;const u=(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?zl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return zl;const n=Hl(e,r);if(-1!==n)return Wl(e,r,n)?{encoding:r,skip:0}:zl;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:Wl(e,r,n)?o:zl}if(-1===i)return t?zl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?zl:void 0;if(0===e[i+1])return o}return zl},d=e=>{if(e===r)return"";const t=o().end();return r=e,t},h=e=>"utf8"===r&&0!==e&&e<128,p=(e,n)=>{let p="",f=e;for(;;){if(i){const e=Math.min(f.length,512-a.length);let r;if(r=a.length>0?Buffer.concat([a,f.subarray(0,e)]):e===f.length?f:f.subarray(0,e),0===r.length)return p;const o=u(r,n||r.length>=512);if(void 0===o)return 1===r.length&&h(r[0])&&(p+=t.write(r),c=!0),a=Buffer.from(r),p;let m=o.skip,g=!1;if(c&&(m="utf8"===o.encoding?1:2,g=r[0]===Ll,c=!1),0===a.length)m>0&&(f=f.subarray(m));else{const t=r.subarray(m);f=f.subarray(e),f=0===f.length?t:0===t.length?f:Buffer.concat([t,f]),a=Ul}if(i=g,l=0,s=void 0,p+=d(o.encoding),g)continue}if(0===f.length)return p;if("utf8"===r&&!f.includes(0)&&!f.includes(254)&&!f.includes(255)){const e=f.lastIndexOf(Ll),r=-1===e?-1:f.length-e-1;if(-1===r||r>=2)return p+t.write(f);if(i=!0,0===r)return e>0&&f[e-1]===Ll&&(a=Buffer.of(Ll),c=!0),p+t.write(f);const n=f[f.length-1];return a=Buffer.of(n),c=h(n),p+t.write(c?f:f.subarray(0,e+1))}const e=Hl(f,r,l,s);if(-1===e)return l+=f.length,s=f[f.length-1],p+o().write(f);p+=o().write(f.subarray(0,e)),f=f.subarray(e),i=!0}};return{write:e=>0===e.length?o().write(e):p(e,!1),peek(){if(!i||0===a.length)return"";const t=u(a,!0);if(void 0===t)return"";const r=c?"utf8"===t.encoding?1:2:t.skip,n=a.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):ql(t.encoding).write(n)},end(){const e=p(Ul,!0)+o().end();return i=!0,a=Ul,c=!1,l=0,s=void 0,e}}}var Vl=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},Kl=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 Jl=(0,C.h)("local-exec:shell-core"),Zl="win32"===process.platform,Xl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Ql(e){return`'${e.replace(/'/g,"'\\''")}'`}const Yl=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function eu(e){return Yl.some((t=>e.includes(t)))?(0,Js.createHash)("sha256").update(e).digest("hex"):e}function tu(e,t){return e[t]??process.env[t]}const ru=/^[A-Za-z_][A-Za-z0-9_]*$/,nu=/CURSOR_SANDBOX/i;function ou(e){return ru.test(e)&&!nu.test(e)}function su(e){return"function"==typeof e?e():e}function iu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function au(e){let t=0,r=0;const n=e.length;for(;rou(e)&&!r.includes(e))),o=`builtin unset ${[...Xl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Xl){const r=tu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Ql(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Ql(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("; ")}(y,b),void 0!==y.__CURSOR_SANDBOX_ENV_RESTORE&&(y.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=eu(e);t!==e&&(r=r.split(e).join(t))}return r}(y.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,S,b.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const k=function(e,t){const r=tu(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[]}}(tu(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=iu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=iu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=iu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=iu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,y),_=(0,ri.CG)(k??ri.BM);let C,E,x;k&&(yield{type:"start",sandboxed:"workspace_readonly"===_||"workspace_readwrite"===_}),t.askpassConfig&&!Zl&&(y.SUDO_ASKPASS=t.askpassConfig.helperPath,y.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,y.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=(this.options.outputFallbackEncoding??(()=>$l.current()))(),I=()=>function(e){if(void 0===e)return Fl();const t=Al.get(e);return void 0!==t&&pa.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=Dl.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&&jl.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Ml,i=0,a="utf8";const c=()=>{a="utf8",o.reset(),i=0},l=(t,n)=>{const s=n?Ol(t):0,c=t.subarray(0,t.length-s),l=c.toString("utf8");if("replacement"!==a){const t=c.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===l.length?"":l[l.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,u=function(e,t,r){let n=Nl(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s{const t=0===s.length?e:Buffer.concat([s,e]);if(s=Ml,"utf8"===a){const e=t.subarray(0,t.length-Ol(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(c(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(l.length))),-1===e?o.note(n):c(),i=u;continue}a="undecided"}const{text:h,keep:p}=l(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&c(),i=u}return r},end:()=>{const e=s;s=Ml;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):l(e,!1).text;return c(),t}}}(e,t):Fl()}(P),R={stdout:Gl(I),stderr:Gl(I)},T=e=>{void 0!==u&&0!==e.length&&(u.file?u.file.write(e):u.buffer+=e)},A=function*(){const e={stdout:f,stderr:m};for(const t of["stdout","stderr"]){const r=R[t].end();0!==r.length&&(void 0!==u&&!0!==u.truncated&&T(r),e[t]||(yield{type:t,data:r}))}};for await(const r of a.execute(e,t.command,{signal:w,workingDirectory:l,env:y,sandboxPolicy:k,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:su(this.options.powershellUtf8Console),powershellUtf8ChildEnv:su(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:su(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:su(this.options.powershellWebRequestUtf8)})){C=0,E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=R[r.type],o="stdout"===r.type?f:m,i=void 0===u||!0===u.truncated;let a=!1;if(!o||!i){C=r.data.length;const c="stdout"===r.type?h:p,l=!o&&c+C<=_i,f=void 0!==u&&!0!==u.truncated&&u.size+C<=fl;"stdout"===r.type?e=l:t=l;const m=!o&&!l,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&T(x),m||(x="")),(l||f)&&(E=n.write(r.data),a=!0),void 0!==u&&u.size+C>fl)u.truncated=!0;else if(f&&void 0!==u)if(u.size+=C,u.lineCount+=au(r.data),u.file)u.file.write(E);else if(u.buffer+=E,u.size>u.threshold){const e=s.default.join(this.projectDir,pl);u.path=s.default.join(e,`${(0,Js.randomUUID)()}.txt`);try{await(0,Ys.mkdir)(e,{recursive:!0}),u.file=(0,ti.createWriteStream)(u.path),u.file.on("error",(e=>{d??=e})),u.file.write(u.buffer)}catch(e){d??=e instanceof Error?e:new Error(String(e)),u.truncated=!0}u.buffer=""}}a||n.end()}switch(r.type){case"stdout":e?(h+=C,E&&(yield{type:"stdout",data:E})):f||(x&&(yield{type:"stdout",data:x}),f=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:ri.Ls});break;case"stderr":t?(p+=C,E&&(yield{type:"stderr",data:E})):m||(x&&(yield{type:"stderr",data:x}),m=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*A();const e=Math.max(0,Math.round(performance.now()-o));let t;if(u?.file){if(u.truncated){const e=`\n... (output truncated at ${u.size} bytes) ...\n`;u.file.write(e),u.size+=e.length,u.lineCount+=ma(e)-1}const e=await new Promise((e=>u.file.end(e)));d??=e??void 0,d?await(0,Ys.rm)(u.path,{force:!0}):t=new yl.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})}d&&void 0!==u?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${u.path}: ${d.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*A()}catch(e){r.error=e,r.hasError=!0}finally{Kl(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 uu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Vl(r,(0,i.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Jl.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{Kl(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class du{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 hu(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(sa(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function pu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return sa(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 fu(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new xr.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new xr.pZ({command:e,workingDirectory:t,reason:pu(r)})}}var mu=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 gu=(0,C.h)("local-exec:background-shell");function wu(e,t,r){return new Cr.Lt({result:fu(e,t,r)})}class yu{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 vu(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 bu(e){e().catch((()=>{}))}class Su{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=vi.L3.compile(e.config.pattern,vi.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=mi(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}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:Date.now()-this.startedAtMs}),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=pe(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:`${fi(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=pe(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&&gu.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 ku{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 Su({shellId:t,outputPath:i,config:o,conversationId:r??he,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&gu.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 _u{async spawn(e,t){const r=new AbortController,n=new yu(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 ri.SandboxUnsupportedError||e instanceof cu)throw e}return bu((()=>vu(n,o))),n}async adopt(e){const t=new yu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,bu((()=>vu(t,e.eventIterator))),t}}function Cu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Eu(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: ${Cu(e.cwd)}\n`,n+=`command: ${Cu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${Cu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function xu(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 Pu{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Ys.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();let g,w="running",y=!1,v=Promise.resolve();const b=async e=>{if(c)try{await c.write(e)}catch(e){}},S=t.shellId,k=s.join(r,`${S}.txt`),_=async()=>{if(!a)return;const e=Date.now()-f,r=Eu({pid:g,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},C=()=>(v=v.then(_).catch((()=>{})),v),E=()=>{void 0!==l&&(clearInterval(l),l=void 0)},x=async e=>{if(p)return;p=!0,g=e;const r=Date.now()-f,n=Eu({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:r});await(0,Ys.writeFile)(k,n,"utf8"),l=setInterval((()=>{C()}),5e3)},P=async()=>{a||(a=await ti.promises.open(k,"r+")),c||(c=await ti.promises.open(k,"a"))},I=async(e,t)=>{if(!y){if(y=!0,E(),p||await x(),await P(),void 0!==t){const e=Date.now()-f,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(r)}w=e,await C()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await x(),await P()),await b(r.data);else if("stderr"===r.type)p||(await x(),await P()),await b(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 x(r.pid),await P());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`;b(`[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 x(),await P(),await b(xu("stderr"));else d=!0,p||await x(),await P(),await b(xu("stdout"));yield r}if(!y){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=Cu(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(E(),await v,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,Ys.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString();let i="running";const a=Date.now()-n,c=Eu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:a})+(e.initialOutput??"");await(0,Ys.writeFile)(r,c,"utf8");const l=await ti.promises.open(r,"r+");let u;try{u=await ti.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=!1,f=!1,m=Promise.resolve();const g=async()=>{const t=Date.now()-n,r=Eu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:o,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},w=()=>(m=m.then(g).catch((()=>{})),m);let y=setInterval((()=>{w()}),5e3);const v=()=>{void 0!==y&&(clearInterval(y),y=void 0)},b=async()=>{if(!d){d=!0,v(),await m;try{await l.close()}catch{}try{await u.close()}catch{}}},S=async e=>{try{await u.write(e)}catch(e){}},k=async(t,r)=>{if(!h){if(h=!0,v(),void 0!==r){const t=Date.now()-n,o=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(o)}i=t,await w()}},_={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await S(e.data):"stdout_trimmed"!==e.type||p?"stderr_trimmed"!==e.type||f?"exit"===e.type&&(await k(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await b()):(f=!0,await S(xu("stderr"))):(p=!0,await S(xu("stdout")))}return t.done&&await b(),t}catch(t){const r=e.abortController.signal.aborted;throw await k(r?"aborted":"failed"),await b(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}return await b(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:_})}}class Iu{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:de(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??he,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:Date.now()-o,...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.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},n,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.startTime,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 Ru{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 Tu{constructor(e,t,r,n,o,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new Ru(s,i):s,c=o??function(e){const t=new _u;return new Pu(t,e)}(n),l=new ku(c,n,a);this.backgroundShellManager=new Iu(l,a)}getManager(){return this.backgroundShellManager}dispose(){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,i.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Gi(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=(0,bi.o1)(s),c=new xr.HO(li(n).structured),l=ia({command:n,parsingResult:c,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new Cr.Lt({result:{case:"rejected",value:new xr.pZ({command:n,workingDirectory:a,reason:l})}});let u=o;if(gu.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:c.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Hr(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:c,toolCallId:t.toolCallId},o);if("block"===r.kind)return gu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),wu(n,a,r.reason);gu.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:a,timeout:0,parsingResult:c,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t)},o);if("block"===r.kind)return gu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),wu(n,a,r.reason);u=r.policy,gu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(Di()&&(u=Ui(n,c)),u&&"insecure_none"!==u.type){const e=await cl(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),o=u?{perRepo:u}:void 0,s={ctx:e,command:n,workingDirectory:a,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},i=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Cr.Lt({result:{case:"success",value:new Cr.Po({shellId:r,command:n,workingDirectory:a,pid:i.pid})}})}catch(r){if(r instanceof ri.SandboxUnsupportedError){const o=u?.type??"unknown";return gu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Cr.Lt({result:{case:"sandboxUnsupported",value:new xr.rI({command:n,workingDirectory:a,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Cr.Lt({result:{case:"error",value:new Cr.Of({command:n,workingDirectory:a,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{mu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const Au={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},$u=Nn.object({command:Nn.string().optional(),args:Nn.array(Nn.string()).optional(),env:Nn.record(Nn.string(),Nn.string()).optional(),url:Nn.string().optional(),headers:Nn.record(Nn.string(),Nn.string()).optional(),cwd:Nn.string().optional(),envFile:Nn.string().optional(),auth:Nn.object({CLIENT_ID:Nn.string(),CLIENT_SECRET:Nn.string().optional(),scopes:Nn.array(Nn.string()).optional()}).optional(),enabledTools:Nn.array(Nn.string()).optional(),placement:Nn.enum(["server","client"]).optional(),tls:Nn.object({caBundle:Nn.string().trim().min(1).max(131072)}).optional()}),Mu=Nn.object({mcpServers:Nn.record(Nn.string(),$u).optional()}),Du=Nn.enum(["canvas"]),Ou=Nn.array(Du).transform((e=>[...new Set(e)].sort()));class Fu extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Nu(e){const t=e.trim();if(!t)throw new Fu("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Fu("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Fu("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Fu("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 Fu("Missing plugin name before @",e);if(!s)throw new Fu("Missing source after @",e);if(!r.test(o))throw new Fu("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Fu("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 Fu("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 Fu("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 Fu("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new Fu("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 Fu("Missing marketplace name",e);if(!r.test(a))throw new Fu("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function ju(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 Lu(e){return e.sourceInfo.name}function Uu(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Bu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Wu(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const Hu=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function qu(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=>Hu.has(e)))}const zu=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Gu=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Vu=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Ku(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Vu.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Ju(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Ju(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Ju(r,t)}else for(const[,r,n,o]of e.matchAll(zu)){const e=r??n;if(void 0===e||Gu.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Zu(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Ju(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:Ku(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.`,...qu(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var Xu=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const Qu=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Yu=/^v?(\d+\.\d+(?:\.\d+)?)$/;function ed(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 td(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Yu.exec(e);if(null!==t)return t[1]}}function rd(e){return void 0===e?{kind:"absent"}:Qu.has(e)?{kind:"supported",id:e,version:td(e)??e}:{kind:"unsupported",id:e}}const nd=10485760,od=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,sd=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],id=[".cursor-plugin",".claude-plugin"],ad=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],cd=Nn.object({source:Nn.literal("github"),repo:Nn.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ld=Nn.object({source:Nn.literal("url"),url:Nn.string().url().endsWith(".git","URL must end with .git"),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),ud=Nn.object({source:Nn.literal("git-subdir"),url:Nn.string().url().endsWith(".git","URL must end with .git"),path:Nn.string().min(1),ref:Nn.string().optional(),sha:Nn.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),dd=Nn.union([Nn.string(),cd,ld,ud]),hd=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,pd='Must be a semver version (X.Y.Z) or "never"',fd=Nn.object({cursor:Nn.string().regex(hd,pd).optional(),sand:Nn.string().regex(hd,pd).optional(),sandMobile:Nn.string().regex(hd,pd).optional()}),md=Nn.object({name:Nn.string().min(1,"Author name is required"),email:Nn.string().email().optional()}),gd=Nn.enum(["string","number","integer","boolean","object","array","null"]),wd=Nn.union([gd,Nn.array(gd).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Nn.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function yd(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Nn.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:Nn.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:Nn.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:Nn.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:Nn.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:Nn.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:Nn.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const vd=Nn.lazy((()=>Nn.object({type:wd.optional(),title:Nn.string().optional(),description:Nn.string().optional(),format:Nn.string().optional(),writeOnly:Nn.boolean().optional(),placeholder:Nn.string().optional(),default:Nn.unknown().optional(),enum:Nn.array(Nn.any()).nonempty().optional(),const:Nn.unknown().optional(),properties:Nn.record(Nn.string(),vd).optional(),required:Nn.array(Nn.string()).optional(),additionalProperties:Nn.union([Nn.boolean(),vd]).optional(),items:Nn.union([vd,Nn.array(vd)]).optional(),minLength:Nn.number().int().nonnegative().optional(),maxLength:Nn.number().int().nonnegative().optional(),minimum:Nn.number().optional(),maximum:Nn.number().optional(),exclusiveMinimum:Nn.number().optional(),exclusiveMaximum:Nn.number().optional(),multipleOf:Nn.number().positive().optional(),minItems:Nn.number().int().nonnegative().optional(),maxItems:Nn.number().int().nonnegative().optional(),uniqueItems:Nn.boolean().optional(),minProperties:Nn.number().int().nonnegative().optional(),maxProperties:Nn.number().int().nonnegative().optional()}).strict().superRefine(yd)));function bd(e){const t=vd.superRefine(((e,t)=>{_d(e)&&"object"===e.type||t.addIssue({code:Nn.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?Cd(t.data)?{success:!0,data:t.data}:{success:!1,error:new Nn.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const Sd=Nn.unknown().superRefine(((e,t)=>{const r=bd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!Cd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),kd=(Nn.object({name:Nn.string().min(1).transform((e=>e.toLowerCase())).refine((e=>od.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Nn.string().optional(),source:dd,description:Nn.string().optional(),version:Nn.string().optional(),author:md.optional(),publisher:Nn.string().min(1).optional(),homepage:Nn.string().url().optional(),repository:Nn.string().url().optional(),license:Nn.string().optional(),keywords:Nn.array(Nn.string()).optional(),capabilities:Ou.optional(),logo:Nn.string().optional(),category:Nn.string().optional(),tags:Nn.array(Nn.string()).optional(),minClientVersions:fd.optional(),strict:Nn.boolean().default(!0),commands:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),agents:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),skills:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),rules:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),hooks:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]).optional(),variables:Sd.optional(),mcpServers:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown()),Nn.array(Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]))]).optional()}),Nn.object({description:Nn.string().optional(),version:Nn.string().optional(),pluginRoot:Nn.string().optional()}),Nn.object({name:Nn.string().min(1).regex(od,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Nn.string().optional(),description:Nn.string().optional(),version:Nn.string().optional(),author:md.optional(),publisher:Nn.string().min(1).optional(),homepage:Nn.string().url().optional(),repository:Nn.string().url().optional(),license:Nn.string().optional(),logo:Nn.string().optional(),keywords:Nn.array(Nn.string()).optional(),capabilities:Ou.optional(),minClientVersions:fd.optional(),commands:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),agents:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),skills:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),rules:Nn.union([Nn.string(),Nn.array(Nn.string())]).optional(),hooks:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]).optional(),variables:Sd.optional(),mcpServers:Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown()),Nn.array(Nn.union([Nn.string(),Nn.record(Nn.string(),Nn.unknown())]))]).optional()}));function _d(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Cd(e){return _d(e)&&"object"===e.type}function Ed(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function xd(e,t){if(_d(e)&&"string"==typeof e.name){const t=Ed(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Ed(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,Js.randomUUID)()}`}(t)}function Pd(e){if(_d(e)&&_d(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 Id(e){return"string"==typeof e?e:void 0}function Rd(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Td(e){return"string"==typeof e?e:Rd(e)}function Ad(e){if(!_d(e)||!_d(e.metadata))return;const t={description:Id(e.metadata.description),version:Id(e.metadata.version),pluginRoot:Id(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function $d(e){if(!_d(e))return;const t=Id(e.name);if(void 0===t||0===t.length)return;const r=Id(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Md(e){if("string"==typeof e||_d(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||_d(e)));return t.length>0?t:void 0}}function Dd(e){if("string"==typeof e||_d(e))return e}function Od(e){if(void 0===e)return;const t=bd(e);return t.success?t.data:void 0}function Fd(e,t={}){if(e.length>nd)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(!_d(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(!_d(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:_d(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Id(n.ref),sha:Id(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Id(n.ref),sha:Id(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:Id(n.ref),sha:Id(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Id(n.ref),sha:Id(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Id(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?Ed(e.name):"")||function(e){if("string"==typeof e){const t=Ed((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Ed(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Ed((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=Ed((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=Ou.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=fd.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:Id(e.displayName),source:r,description:Id(e.description),version:Id(e.version),author:$d(e.author),publisher:Id(e.publisher),homepage:Id(e.homepage),repository:Id(e.repository),license:Id(e.license),keywords:Rd(e.keywords),logo:Id(e.logo),category:Id(e.category),tags:Rd(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Td(e.commands),agents:Td(e.agents),skills:Td(e.skills),rules:Td(e.rules),hooks:Dd(e.hooks),variables:Od(e.variables),mcpServers:Md(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:xd(r,t),owner:Pd(r),description:Id(r.description),plugins:n,metadata:Ad(r),skippedPluginEntries:o}}}function Nd(e){if(e.length>nd)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=rd(ed(t)),n=kd.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 jd(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 Ld(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function Ud(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new Xu.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var Bd=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Wd=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Hd=/\$%7B([^%/?#]+?)%7D/gi;function qd(e,t){return zd(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 zd(e,t){if("string"==typeof e)return function(e,t){return e.replace(Hd,"${$1}").replace(Wd,((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=>zd(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]=zd(o,t);return r}return e}function Gd(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Vd=[".mcp.json","mcp.json"],Kd=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Jd(e,t){if(!function(e){return Kd.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 Zd(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Xd(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Vd.map((e=>void 0!==t?`${t}/${e}`:e))}function Qd(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=Gd(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Gd(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?Gd(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Gd(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return qd(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return qd(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 Yd(e,t,r){try{const n=(0,Bd.qg)(e),o=ed(n);if(void 0!==o){const e=r?.log??Au;"unsupported"===rd(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=td(e),n=td(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=Mu.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Qd(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Jd(e,t)&&Zd(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Mu.safeParse({mcpServers:a});if(e.success)return i?e.data:Qd(e.data,t,r)}return null}catch{return null}}function eh(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function th(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Vd,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Yd(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(!Ld(i))return;const a=await t(i);if(null===a)return;const c=Yd(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&eh(s,c.mcpServers,n(i))},a=e=>{const t=Yd(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&eh(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}}}function rh(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}var nh=r("node:stream"),oh=r("node:stream/promises"),sh=r("node:zlib"),ih=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const ah=".cache-complete";function ch(e){return nr(e)}function lh(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function uh(e,t){return function(e,t,r,n){const o=[t,r];return void 0!==n&&o.push(n),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...o):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...o].join("/"):(0,s.join)(e,...o)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?ch(t.version):void 0)}class dh{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return uh(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=lh({parent:t,name:ah});return(await(0,Ys.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,Ys.mkdir)(t,{recursive:!0});const r=nh.Readable.from(e.tarball);return await(0,oh.pipeline)(r,(0,sh.createGunzip)(),(0,ih.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=uh(this.cacheRoot,e);try{return(await(0,Ys.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Ys.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=uh(this.cacheRoot,e);await(0,Ys.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=>ch(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,Ys.writeFile)(lh({parent:t,name:ah}),"")}}function hh(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 ph=[["safe.bareRepository","explicit"]],fh=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],mh=[["core.quotePath","false"]];function gh(e){const t="allow-hooks"===e?fh.filter((([e])=>"core.hooksPath"!==e)):fh;return[...ph,...t]}const wh=(0,ha.promisify)(bl.execFile),yh=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),vh=new Set(["diff","show","blame","log","whatchanged"]);function bh(e){for(let t=0;tArray.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});return Ch("git",[...Eh(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const Ih=/^[0-9a-f]{7,40}$/i,Rh=/^[0-9a-f]{40}$/i;function Th(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 Ah(e,t,r){const n=t.trim();if(Rh.test(n))return{fullSha:n.toLowerCase()};if(Ih.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Ph(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Th(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 Ph(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Th(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 Ph(["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=Th(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const $h=ad.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 Mh;function Dh(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 Oh(e){const t=[];for(const r of e){const e=Dh(r);if(null===e)return"all";t.push(e)}return t}async function Fh(e,t){const r="all"===e?"all":Oh(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Mh??=(async()=>{try{const{stdout:e}=await Ph(["--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}})(),Mh));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...$h,...o])]):[]};var o}function Nh(e){return e.toLowerCase().includes("filtering not recognized by server")}async function jh(e,t,r){await Ph(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Lh(e){try{await(0,Ys.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Ph(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Uh(e,t,r){if("all"!==t&&0===t.length)return;if(!await Lh(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Ph(["sparse-checkout","disable"],n);const o=Oh(t);"all"!==o?await Ph(["sparse-checkout","add","--",...o],n):await Ph(["sparse-checkout","disable"],n)}(0,Ei.J)((function(){Mh=void 0}));const Bh=/\.git$/i,Wh=new Set(["account","dashboard"]);function Hh(e){return e.replace(Bh,"")}function qh(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function zh(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Gh(e){return e.toLowerCase().split(".").includes("gitlab")}function Vh(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function Kh(e){const t=e.toLowerCase();return Gh(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function Jh(e){return zh(e)?"github":Gh(e)?"gitlab":Vh(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function Zh(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);Wc(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=Hh(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:Jh(r),owner:s.owner,repo:s.repo,host:r}}function Xh(e){const t=Qh(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 Qh(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function Yh(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=Zh(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Gh(r.host)){const e=Qh(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=Hh(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=Qh(e.trim());if(null!==t&&Vh(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=qh(t),o=qh(r);if(void 0===n||void 0===o||Wh.has(n.toLowerCase()))return;const s=Hh(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=Qh(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=Hh(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!Wc(e.host)&&null===Kh(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=tp(r.host.replace(/^www\./i,""));return{url:`https://${e}/${Xh(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=Kh(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function ep(e){const t=Yh(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 tp(e){return zh(e)?"github.com":e}function rp(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 np(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function op(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}const sp=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 ip(e){const t=nr(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":sp.has(t.toLowerCase())?`_${t}`:t}const ap=18e5,cp=6e5,lp={recursive:!0,force:!0,maxRetries:3},up=["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"],dp=["enotempty: directory not empty, rename","/_staging/"],hp=["upload-pack: not our ref","server does not allow request for unadvertised object"];function pp(e){const t=String(e).toLowerCase().replaceAll("\\","/");return up.some((e=>t.includes(e)))?"user_git_access":dp.every((e=>t.includes(e)))?"local_cache_race":hp.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function fp(e){return"object"==typeof e&&null!==e&&(!0===e.killed||fp(e.cause))}function mp(e){return fp(e)?"killed_by_budget":pp(e)}function gp(e){const t=Yh(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=Zh(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:tp(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const wp=new Map;class yp{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?ap:void 0}localTimeoutMs(){return this.sparsePluginClones?cp:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...xh(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Fh(n?.materialize??"all",this.sparsePluginClones);await Ph(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await jh(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Ph(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Ph(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Nh(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,Js.randomUUID)());return await(0,Ys.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Ys.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Ys.rm)(t,lp),await(0,Ys.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Ys.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,Ys.stat)(n);r-o.mtimeMs>yp.STALE_STAGING_THRESHOLD_MS&&await(0,Ys.rm)(n,lp)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,ip(e),ip(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=gp(e);return(0,s.join)(this.cacheRoot,ip(r),...n.map(ip),ip(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=gp(e);return(0,s.join)(this.cacheRoot,ip(t),...r.map(ip))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=ip(t);try{const e=await(0,Ys.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Ys.rm)((0,s.join)(n,e.name),lp))))}catch{}if(void 0!==r)try{await(0,Ys.rm)(r,lp)}catch{}}async ensureCloned(e,t,r,n=Au,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=Au){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Uh(e,t,{extraGitConfig:xh(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:mp(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:mp(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=(wp.get(r)??Promise.resolve()).catch((()=>{})).then(t);wp.set(r,n);try{return await n}finally{wp.get(r)===n&&wp.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:ep(t);if(null!==a)try{i=(await Ah(a,s,{sshBatchMode:!0,extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&fp(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:pp(e)}),a=null,i=(await Ah(t,s,{extraGitConfig:xh(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Ah(t,s,{extraGitConfig:xh(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 Lh(c);return e&&await Uh(c,o,{extraGitConfig:xh(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,Ys.utimes)(l,e,e).catch((()=>{}))}),yp.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&&fp(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:mp(e)}),await(0,Ys.rm)(l,lp),await(0,Ys.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=mp(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,Ys.rm)(l,lp)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Ys.stat)(e)).isDirectory())return!1;const t=await(0,Ys.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Ys.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return op(e,t)}async copyPluginToDir(e,t){await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.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 ad){const n=(0,s.join)(e,r);let o;try{o=await(0,Ys.readFile)(n,"utf-8")}catch{continue}const i=Fd(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=jd(n.source,r.metadata?.pluginRoot);return o&&Ld(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=jd(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":Ld(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):[]}}yp.STALE_STAGING_THRESHOLD_MS=3e5,yp.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const vp=(0,ha.debuglog)("cursor-plugins");function bp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Sp(e){return bp(e)?e:void 0}function kp(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function _p(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 Cp(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Op(e,t.gitUrl)?e:r:e}function Ep(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function xp(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=_p(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Pp="backend-git://";function Ip(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Pp}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Rp(e){if(!e.startsWith(Pp))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 Tp="backend-release://";function Ap(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Tp}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function $p(e){if(!e.startsWith(Tp))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 Mp=/^[0-9a-f]{7,40}$/i;function Dp(e){let t;try{t=gp(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Op(e,t){if(e.trim()===t.trim())return!0;const r=Dp(e),n=Dp(t);return null!==r&&r===n}const Fp=104857600;async function Np(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(!(bp(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>bp(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>Fp)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||!jp(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||!jp(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>Fp)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,Js.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,Ys.mkdir)(n,{recursive:!0});const u=await(0,Ys.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,Ys.writeFile)(d,c),await(0,Ys.mkdir)(h,{recursive:!0});let e=0,t=0;await ih.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,Ys.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,Ys.readdir)(e)).some((e=>id.includes(e)))&&(a=e)}const p=await(0,Ys.readdir)(a);await Promise.all(p.map((e=>(0,Ys.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Ys.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function jp(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Lp{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??Au,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new yp(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=xh(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:ep(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 Ah(e,t,n):await Ah(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&fp(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}};for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=_p(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=kp({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;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,Js.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:Sp(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=Cp(c,r),d=xp(e,o),h=hh(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?Ap({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Ip(g,d,t.gitPath??void 0);const w=Ep(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Op(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:Ip(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:Sp(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}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=Rp(e.downloadUrl);return!(!r||!Op(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Ys.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Ys.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${nr(t.name)}.md`,o=[];o.push(`description: ${np(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${np(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Ys.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,Ys.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${nr(t.name)}.md`,o=t.description?`---\ndescription: ${np(t.description)}\n---\n\n`:"";await(0,Ys.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,Ys.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&rp(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,Ys.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,Ys.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,Ys.mkdir)(c,{recursive:!0}),await(0,Ys.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,Ys.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===$p(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)&&fp(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=Au,n,i){const a=i?.sparsePluginClones??!1,c=a?ap:void 0,l=$p(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Np(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=op(r,e.gitPath);await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Ys.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Np(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Rp(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Au,o,s="all",i=!1){const a=performance.now(),c=Mp.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?ap:void 0,h=i?cp:void 0,{sparse:p,sparseDirs:f}=await Fh(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await jh(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Ph(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Ph(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Ph(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Ph(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Ph(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Ph(["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:ep(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&fp(t))throw t;await(0,Ys.rm)(r,{recursive:!0,force:!0}),await(0,Ys.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Nh(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);vp("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?Oh([u.gitPath]):[],a),u.gitPath)o=op(d,u.gitPath);else{const t=await async function(e,t){for(const r of ad){const n=(0,s.join)(e,r);let o;try{o=await(0,Ys.readFile)(n,"utf-8")}catch{continue}const i=Fd(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=jd(c.source,a.metadata?.pluginRoot);return l&&Ld(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 Uh(d,Oh([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=op(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 Uh(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Ys.mkdir)(t,{recursive:!0}),await(0,Ys.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Ys.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,xh(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=Oh(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?Oh([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,Oh([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 Up(e,t,r,n,o){return new Lp(e,t,r,n,o)}var Bp=r("node:url"),Wp=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Hp=()=>({});function qp(e,t){return Wp(e,{...t,engines:{...t?.engines,js:Hp,javascript:Hp}})}function zp(e,t,r){return Wp.stringify({content:e,data:{}},t,r)}function Gp(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Vp(e,t){if(Object.hasOwn(e,t))return e[t]}function Kp(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?Gp(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===Vp(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Gp(t.projectPath)===a&&!0===Vp(i,e))))),r||!0!==Vp(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 Jp=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");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=Jp.Ay.load(t[1],{schema:Jp.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=Vd.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(!Ld(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(!Ld(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(!Ld(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=>th(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:Zu(a??i),configs:l}}}function af(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cf(e){return!!af(e)&&(void 0===e.enabledPlugins||af(e.enabledPlugins))}function lf(e){return JSON.parse(e)}function uf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function df(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=lf(await(0,Ys.readFile)(n,"utf-8"));cf(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=lf(await(0,Ys.readFile)(o,"utf-8"));cf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}async function hf(e){try{return(await(0,Ys.lstat)(e)).isSymbolicLink()}catch{return!1}}async function pf(e){if(await hf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Ys.readFile)(e,"utf-8")}async function ff(e){if((await(0,Ys.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function mf(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 gf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Ys.realpath)(e),n=op(t,r),o=await(0,Ys.realpath)(n);if(op(t,o),!(await(0,Ys.stat)(o)).isFile())return;return await ff(o),(0,Bp.pathToFileURL)(o).href}catch{return}}function wf(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 yf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function vf(e,t){return wf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function bf(e,t,r){let n;for(const o of sd){const i=(0,s.join)(e,o);let a;try{if(await hf(i))continue;if(!(await(0,Ys.stat)(i)).isFile())continue;await ff(i),a=await pf(i)}catch{continue}const c=Nd(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 gf({installPath:e,logo:l.logo}),S=wf(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&&!yf(S))continue;if(!g&&!C){n=n?{...n,fields:vf(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=vf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||yf(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 Sf(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,Ys.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return op(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,Ys.realpath)(t);try{return op(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,Ys.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,Ys.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 ff(i);const l=await(0,Ys.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,Ys.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([kf(r,o.skills,e),Cf(r,o.agents,e),Ef(r,o.commands,e),_f(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function kf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Pf({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}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=Pf({content:Gd(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Cf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=If({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Ef(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rf({content:Gd(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function xf(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 Pf({content:e,relativePath:t}){try{const r=qp(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:xf(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function If({content:e,relativePath:t}){try{const n=qp(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 Rf({content:e,relativePath:t}){try{const r=qp(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 Tf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Af(e,t,r){const n=r??Tf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of sd){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=ed(a);const c=Nd(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return th(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ld(t))return null;const r=(0,s.join)(e,t);try{return await hf(r)?null:(await(0,Ys.stat)(r)).isFile()?(await ff(r),await pf(r)):null}catch{return null}}}(e),{fallbackFileNames:Xd(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function $f(e,t,r){const n=await Af(e,void 0,{log:r});if(n)return n;for(const n of ad){const o=(0,s.join)(e,n);try{if(!(await(0,Ys.stat)(o)).isFile())continue;const n=await(0,Ys.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Of(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Ff),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(!Ld(n))continue;const o=(0,s.join)(e,n);try{await ff(o);const t=Yd(await pf(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 Mf=new Set(Object.values(ke));function Df(e){return Mf.has(e)}function Of(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ff(e){return!(!Of(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Nf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Df(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Gd(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Gd(e.prompt,t)}:e)));return{...e,hooks:r}}async function jf(e,t,r,n){if("object"==typeof r){const o=Lf(r,t);return o&&"config"in o?{config:Nf(o.config,e),...void 0!==n&&{sourcePath:n}}:o}let o,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!Ld(t))return;o=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else o=(0,s.join)(e,"hooks","hooks.json");try{if(await hf(o))return;if(!(await(0,Ys.stat)(o)).isFile())return}catch{return}try{await ff(o),i=await(0,Ys.readFile)(o,"utf-8")}catch{return}try{a=JSON.parse(i)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${o}: invalid JSON`}}}const c=Lf(a,t);return c&&"config"in c?{config:Nf(c.config,e),sourcePath:o}:c}function Lf(e,t){const r=function(e){if(!Ae(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(Ae(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"===r){const r=St(e);return r.isValid&&St(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===r){if(!(Of(n=e)&&Of(n.hooks)&&Object.keys(n.hooks).length>0))return;const r=Ne(e.hooks),o=St(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}var n}async function Uf(e,t,r,n){const o=n?.log??Au,s=await bf(e,t,o),i={...Tf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Sf(e,s?.manifestOptions),Af(e,r,i),jf(e,t,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 Bf(e,t,r){const n=r?.log??Au,o=await bf(e,t.raw,n),[s,i,a]=await Promise.all([Sf(e,o?.manifestOptions),$f(e,t,n),jf(e,t.raw,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 Wf(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 Uf(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 Hf(e,t,r={}){const n=r.log??Au,o=performance.now(),i=await async function(e){const t=uf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=lf(await(0,Ys.readFile)(r,"utf-8"));return af(n=e)&&af(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=uf(e),r=(0,s.join)(t,"settings.json");try{const e=lf(await(0,Ys.readFile)(r,"utf-8"));return cf(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 Kp(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=Kp(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 df(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=Nu(e),s=await Bf(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(Nu(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}async function qf(e){const t=e.log??Au,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new dh(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))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,Ys.mkdir)(o,{recursive:!0});try{await n.installPlugin(e,o),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,Ys.rm)(o,{recursive:!0,force:!0})}catch{}throw e}s=o}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await Wf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const n=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:n.message,errorType:mf(n)});const o=e.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:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:o,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,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 zf(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 Gf(e){return zf(e)??`path:${e.installPath}`}function Vf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Kf(e,t){const r=[];for(const o of e){const e=ju(o.identifier),i=`plugin:${e}`,a=Lu(o.identifier),c=Uu(o.identifier),l=Bu(o.identifier),u=Wu(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}(0,s.join)((0,o.homedir)(),".claude","plugins","marketplaces");const Jf=Nn.object({path:Nn.string(),name:Nn.string().optional(),description:Nn.string().optional(),globs:Nn.array(Nn.string()).optional(),alwaysApply:Nn.boolean().optional(),content:Nn.string(),environments:Nn.array(Nn.string()).optional(),disabledEnvironments:Nn.array(Nn.string()).optional()}),Zf=Jf.extend({name:Nn.string()}),Xf=Nn.object({path:Nn.string(),name:Nn.string(),description:Nn.string().optional(),tools:Nn.array(Nn.string()).optional(),model:Nn.string().optional(),prompt:Nn.string(),permissionMode:Nn.enum(["default","readonly"]).optional()}),Qf=Nn.object({path:Nn.string(),name:Nn.string(),description:Nn.string().optional(),argumentHint:Nn.string().optional(),content:Nn.string()}),Yf=Nn.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),em=Nn.object({config:Yf,sourcePath:Nn.string().optional()}),tm=Nn.custom((e=>"object"==typeof e&&null!==e));function rm(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}}Nn.object({schemaVersion:Nn.number().int(),displayName:Nn.string().optional(),description:Nn.string().optional(),authorName:Nn.string().optional(),skills:Nn.array(Jf),rules:Nn.array(Zf),agents:Nn.array(Xf),commands:Nn.array(Qf),mcpConfig:Mu.extend({mcpServerSourcePaths:Nn.record(Nn.string(),Nn.string()).optional()}).optional(),hooks:em.optional(),hooksError:Nn.string().optional(),capabilities:Nn.array(Nn.string()),variablesSchema:tm.optional()}),Error;class nm extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function om(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sm(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function im(e){try{return sm(await(0,Ys.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 am(e){const t=await im(e);return void 0===t?[]:function(e){const t=function(e){const t=sm(e);if(0===t.trim().length)return{};const r=[],n=(0,Bd.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Bd._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new nm(`.cursor/settings.json contains syntax errors: ${e}`)}if(!om(n))return{};const o=n.plugins;if(void 0===o)return{};if(!om(o))return{};const s={};for(const[e,t]of Object.entries(o))om(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||rm(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function cm(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,ha.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,Js.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,Ys.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 Im=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 Rm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Rm(e)}[/\\\\]${Rm(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 Uc,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,i.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),a=(0,s.resolve)(this.userHomeDirectory);if(o===a||da(o,{platform:process.platform,homeDirectory:a}).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 Vc(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 c=this.getThirdPartyExtensibilityEnabled(),l=this.buildIncludeGlobs(c),u={root:this.root,includeGlobs:l,excludeGlobs:Qc,followSymlinks:!0,source:"nested_extensibility"},d={rules:[],skills:[],markdown:[],agents:[]},h=Om.getRipwalkCache();try{const e=h.walk(r.ctx,u);try{for await(const t of e.lines){const e=Dm(t,c);e&&d[e].push((0,s.resolve)(this.root,t))}}finally{h.delete(u)}}catch{}return r.span.setAttribute("nested_extensibility.rules",d.rules.length),r.span.setAttribute("nested_extensibility.skills",d.skills.length),r.span.setAttribute("nested_extensibility.markdown",d.markdown.length),r.span.setAttribute("nested_extensibility.agents",d.agents.length),d}catch(e){t.error=e,t.hasError=!0}finally{Im(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,Ys.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,Ys.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Ys.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,Ys.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 jm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Lm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=Lm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Lm(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,C.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 sc(e)}catch(t){return{skillFilePath:e,error:u(t)}}try{return{skillFilePath:e,content:t,parsed:qp(t)}}catch(t){return{skillFilePath:e,error:d(t)}}}async function Zm(e){const t=await ki(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 fi(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---`:zp("",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 ${f(s.length)} characters; the limit is 64. Rename the skill's folder.`),p.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 ${f(i)} characters; the limit is ${f(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${f(a)} tokens; the recommended limit is ${f(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 m.DX({fullPath:e,content:t,frontmatter:n,type:new m.f5({type:{case:"global",value:new m.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=h(s,og(r));return i?new m.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new m.f5({type:{case:"agentFetched",value:new m.Xo}})}):new m.DX({fullPath:e,content:t,frontmatter:n,type:new m.f5({type:{case:"agentFetched",value:new m.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=xf(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:h(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 m.DX({fullPath:e,parseError:t,type:new m.f5({type:{case:"agentFetched",value:new m.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,ha.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 m.i9};else{const r=xf(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new m.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new m.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new m._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 m.DX({fullPath:e.path,content:e.body,type:new m.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,i.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ha.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,a,c,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=a,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),a),this.ignoreService=l??new ll(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ha.debuglog)("Failed to load cursor rules:",e),[]))),c){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=c.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,ye.q6)(),n=Hm(t,(0,i.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,ha.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new Uc,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(w((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,ha.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 w(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Vc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))try{const e=b(await sc(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else 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,i.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),a=await Vc(n.ctx,this.gitExecutor,o)||o,c=this.loadCursorRulesRule(n.ctx,a).then((e=>e?[e]:[])),l=this.loadRulesFromDirAndAncestors(n.ctx,o);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);u=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else u=[],d=[];const h=(await Promise.all([c,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);const f=[...p.values()];return(await async function(e){const t=e.filter((e=>w((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,Ys.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ki(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=>!w((0,s.basename)(e.fullPath))||i.has(e)))}(f.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,i.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Ys.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await sc(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,i.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,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let a=t;const c=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(a,".cursor","rules"),t=a;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];c&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,a,e));const i=(0,s.dirname)(a);if(i===a)break;a=i}const l=(await Promise.all(o)).flat();return n.span.setAttribute("rules",l.length),l}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,i.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,Ys.stat)(e)).isFile()){const t=y({content:await sc(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 al((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,i.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=b(await sc(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,i.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){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),o=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=gg.getRipwalkCache().walk(n.ctx,e);for await(const t of r.lines){const r=(0,s.join)(e.root,t);o.push(...await this.readRulesAtPath(n.ctx,r))}}catch{}return n.span.setAttribute("rules",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,i.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Ys.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}class wg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[]){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.initialBuiltinSkillsSyncPromise=a,this.getEnabledSkills=p,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,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 f=performance.now();let m=!1,g=!1,w=!1;const y=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-f),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:m})}catch{}return t})).catch((e=>(g=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=y;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(w=!0,this._loaded!==t?this._loaded:(g&&this.closeSeedWindow(e),void 0===r?y:(m=!0,r)))));this.seededLoaded=t,this._loaded=t,y.then((r=>{this._loaded===t?g?w&&this.closeSeedWindow(e):(this._loaded=y,m&&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=>m.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,ye.q6)(),n=Hm(t,(0,i.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,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(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,i.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(o,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(o,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,t))))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([o]));if(this.isIgnoredSkillPath(o)||this.isPrunedByExtensibilityScan(o))return r;const s=t.get(o);if(void 0===s){try{await(0,Ys.stat)(o)}catch{return r}return await this.loadAll(n.ctx)}let i;try{i=await(0,Ys.realpath)(o)}catch{return await this.loadAll(n.ctx)}if(i!==s)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await sc(e);return{skillFilePath:e,content:t,parsed:qp(t)}}(o),realSkillFilePath:i},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=c,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,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(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,i.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const o=[],s=[],a=new Map,c=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),l=new Set(this.getAgentStoreSkillRoots()),u=await Promise.all(this.foldersToWatch.filter((e=>!l.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),d=new Set;for(const e of u)for(const t of e)if(!d.has(t.realSkillFilePath))if(d.add(t.realSkillFilePath),"error"in t)a.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;a.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const h=(await c).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),p=await Promise.all(h.map((e=>ki(e)))),f=[];for(const[e,t]of h.entries()){const r=p[e];d.has(r)||(d.add(r),f.push(t))}const m=await Promise.all(f.map((e=>Zm(e))));for(const e of m)if("error"in e)a.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;a.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:a}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function yg(e){let t;switch(e.type){case"global":t=new m.f5({type:{case:"global",value:new m.i9}});break;case"fileGlobbed":t=new m.f5({type:{case:"fileGlobbed",value:new m.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new m.f5({type:{case:"agentFetched",value:new m.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new m.f5({type:{case:"manuallyAttached",value:new m._u}});break;default:e.type,t=new m.f5({type:{case:"manuallyAttached",value:new m._u}})}return new m.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 vg{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,ha.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=>(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,i.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],a=[];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 Kf(e,(e=>e.skills))}(e),i=function(e){return Kf(e,(e=>e.rules))}(e);for(const e of[...r,...i])o.push(yg(e));for(const t of e){const e=`plugin:${ju(t.identifier)}`,r=Lu(t.identifier),n=Uu(t.identifier),o=Bu(t.identifier),i=Wu(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===qp(c.content).data?.["disable-model-invocation"]}catch{}a.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:i,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",a.length),{rules:o,agentSkills:a}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}const bg=(0,ha.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()?gn.b$.READONLY:gn.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 Nm({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,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,Ys.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await sc(r));if(!o)continue;t.push(new gn.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 Ig=new Set(["claude-code-tutor"]);class Rg{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)Ig.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=Lu(n.identifier),o=Uu(n.identifier),i=Bu(n.identifier),a=Wu(n.identifier);for(const c of n.agents){const l=Vf(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?gn.b$.READONLY:gn.b$.DEFAULT;t.push(new gn.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}}var Ag=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const $g=bl.execFile;function Mg(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,Sl.D9)($g,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ag.w3.UNSPECIFIED,Ag.w3.LEFT,Ag.w3.MIDDLE,Ag.w3.RIGHT,Ag.w3.BACK,Ag.w3.FORWARD,Ag.Dh.UNSPECIFIED,Ag.Dh.UP,Ag.Dh.DOWN,Ag.Dh.LEFT,Ag.Dh.RIGHT;const Dg=(0,ha.promisify)(bl.execFile);function Og(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 Fg(e){const{stdout:t}=await(0,Sl.D9)(Dg,"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:Og(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ag.w3.UNSPECIFIED,Ag.w3.LEFT,Ag.w3.MIDDLE,Ag.w3.RIGHT,Ag.w3.BACK,Ag.w3.FORWARD,Ag.Dh.UNSPECIFIED,Ag.Dh.UP,Ag.Dh.DOWN,Ag.Dh.LEFT,Ag.Dh.RIGHT;const Ng={pattern:"[\\w-]{1,64}",next:e=>e},jg={pattern:"[0-9a-f-]{36}",next:()=>Js.randomUUID()},Lg={pattern:"webp",next:()=>"webp"},Ug={native:[jg,Lg],agent:[Ng,jg,Lg],legacyNative:[jg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Ug).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Ng.pattern}$`),Ag.Z8.NATIVE_X11,Ag.Z8.XDOTOOL,(0,E.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,E.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,E.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,E.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,C.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,E.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Bg=r("../proto/dist/runtime/compact.js");Bg.HL;var Wg=(0,Bg.QT)(sr.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);sr.proto3,sr.proto3,sr.proto3,sr.proto3;class Hg{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:Wg.ARROW,arrow:Wg.ARROW,default:Wg.ARROW,top_left_arrow:Wg.ARROW,hand:Wg.POINTER,hand1:Wg.POINTER,hand2:Wg.POINTER,pointer:Wg.POINTER,pointing_hand:Wg.POINTER,xterm:Wg.TEXT,ibeam:Wg.TEXT,text:Wg.TEXT,watch:Wg.WAIT,wait:Wg.WAIT,progress:Wg.WAIT,left_ptr_watch:Wg.WAIT,crosshair:Wg.CROSSHAIR,cross:Wg.CROSSHAIR,tcross:Wg.CROSSHAIR,move:Wg.MOVE,fleur:Wg.MOVE,size_all:Wg.MOVE,sb_v_double_arrow:Wg.RESIZE_NS,v_double_arrow:Wg.RESIZE_NS,ns_resize:Wg.RESIZE_NS,row_resize:Wg.RESIZE_NS,top_side:Wg.RESIZE_NS,bottom_side:Wg.RESIZE_NS,sb_h_double_arrow:Wg.RESIZE_EW,h_double_arrow:Wg.RESIZE_EW,ew_resize:Wg.RESIZE_EW,col_resize:Wg.RESIZE_EW,left_side:Wg.RESIZE_EW,right_side:Wg.RESIZE_EW,top_left_corner:Wg.RESIZE_NWSE,bottom_right_corner:Wg.RESIZE_NWSE,nwse_resize:Wg.RESIZE_NWSE,size_fdiag:Wg.RESIZE_NWSE,top_right_corner:Wg.RESIZE_NESW,bottom_left_corner:Wg.RESIZE_NESW,nesw_resize:Wg.RESIZE_NESW,size_bdiag:Wg.RESIZE_NESW,not_allowed:Wg.NOT_ALLOWED,no_drop:Wg.NOT_ALLOWED,forbidden:Wg.NOT_ALLOWED,circle:Wg.NOT_ALLOWED,grab:Wg.GRAB,openhand:Wg.GRAB,grabbing:Wg.GRABBING,closedhand:Wg.GRABBING};class zg{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 Hg(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=Wg.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 Mg("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 Mg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return qg[t]??Wg.ARROW}try{const e=await Mg("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 Wg.ARROW}catch{return Wg.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,C.h)("computer-use-lazy");var Gg=r("node:net");function Vg(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 Kg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Jg=Nn.object({rpcSocketPath:Nn.string().min(1).optional(),appControlSocketPath:Nn.string().min(1).optional(),pid:Nn.number().int().positive().optional().catch(void 0),protocolMajor:Nn.number().int().positive().optional().catch(void 0)}).passthrough(),Zg=Nn.object({data:Nn.string(),mimeType:Nn.string().min(1)}).strip(),Xg=Nn.object({message:Nn.string(),screenshot:Zg.optional(),screenshotBefore:Zg.optional(),structuredContent:Nn.unknown().optional(),isError:Nn.boolean()}).strip(),Qg=Nn.object({accessibilityTrusted:Nn.boolean(),screenRecordingGranted:Nn.boolean()}).strip(),Yg=Nn.union([Nn.object({id:Nn.number().int(),result:Xg,ok:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),sessionId:Nn.string().min(1),ok:Nn.literal(!0).optional(),result:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),ok:Nn.literal(!0),result:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int().nullable().optional(),error:Nn.string().min(1),errorCode:Nn.string().min(1).optional(),result:Nn.never().optional(),ok:Nn.never().optional(),permissionStatus:Nn.never().optional(),sessionId:Nn.never().optional()}).strip(),Nn.object({id:Nn.number().int(),permissionStatus:Qg,result:Nn.never().optional(),ok:Nn.never().optional(),error:Nn.never().optional(),errorCode:Nn.never().optional(),sessionId:Nn.never().optional()}).strip()]);function ew(e,t){try{return JSON.parse(e)}catch{throw new Kg(`local-cua ${t} is not valid JSON`)}}const tw={responseMaxBytes:33554432,parseServiceState(e){const t=Jg.safeParse(ew(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Kg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Yg.safeParse(ew(e.toString("utf8"),"RPC response"));if(!r.success)throw new Kg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Kg("local-cua RPC response ID did not match");return r.data}};class rw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function nw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Vg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const ow=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),sw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class iw{constructor(e){this.mode=e}static isInstalled(){if((0,ti.existsSync)(iw.serviceExecutablePath()))return!0;let e;try{e=tw.parseServiceState((0,ti.readFileSync)(iw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||iw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await iw.readServiceState(),t=e?.pid;return void 0!==t&&iw.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!==iw.protocolMajor&&void 0!==e.pid&&!iw.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;iw.throwIfAborted(e.signal);const t=(0,Js.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:iw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw iw.rpcError(r);if(void 0===r.sessionId)throw new rw("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 iw.readServiceState();if(void 0===e)return;const r=await iw.sendOnce(iw.socketPathFrom(e),{id:iw.requestID,method:"control/release",requestID:(0,Js.randomUUID)(),mode:this.mode,sessionId:t},iw.defaultCallTimeoutMs);if(void 0!==r.error)throw iw.rpcError(r)}catch(t){iw.logger.warn(e,"local-cua control release failed",{error:nw(t)})}}}async callTool(e,t,r){iw.throwIfAborted(e.signal);const n=iw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:iw.requestID,method:"tools/call",requestID:(0,Js.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 iw.rpcError(o,t);const s=o.result;if(void 0===s)throw new rw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new rw(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=iw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);iw.throwIfAborted(e.signal);try{return await iw.sendOnce(o,t(),n,e.signal)}catch(o){if(!iw.isPreDeliveryConnectionError(o))throw o;iw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:iw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return iw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await iw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new rw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(iw.throwIfAborted(e.signal),!t){const e=await iw.readServiceState();if(e&&!iw.isExitedIncompatibleHelper(e))return iw.socketPathFrom(e)}await this.launchAndWait(e);const r=await iw.readServiceState();if(!r)throw new rw("local-cua sidecar did not publish service.json after launch");return iw.socketPathFrom(r)}static setLaunchGuard(e){iw.launchGuard=e}async launchAndWait(e){const t=iw.serviceAppPath(),r=iw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){iw.logger.info(e,"launching local-cua sidecar",iw.sidecarLaunchLogFields(t)),"1"===process.env[iw.directLaunchEnv]?await iw.spawnSidecarProcess(e,iw.serviceExecutablePath(),[],{detached:!0}):await iw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+iw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...iw.sharedInstallRelativePath,`${iw.serviceAppBundleName}.app`)}static helperIdentity(){const e=iw.serviceAppPath(),t=process.env[iw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=iw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,ti.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&&sw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??iw.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:ow.get(i.bundleIdentifier))??iw.appSupportFolder)};return(0,ti.existsSync)(a)&&(iw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${iw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,Js.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[iw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return nw(e)}static socketError(e){const t=nw(e);return new rw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return iw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,bl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new rw(`local-cua sidecar launch failed: ${iw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{iw.logger.warn(e,"local-cua sidecar process error after launch",{error:iw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Ys.readFile)(iw.serviceStatePath(),"utf8");return tw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Kg)return;throw new rw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==iw.protocolMajor)throw new rw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${iw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new rw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw iw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(iw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Gg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new rw("local-cua RPC aborted"):iw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new rw(`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(iw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>tw.responseMaxBytes)return void d((()=>s(new rw("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=tw.parseResponse({line:n,expectedID:iw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new rw("local-cua RPC connection failed after request delivery")):()=>s(iw.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 rw(e))))})))}))}}let aw;function cw(){if(void 0===aw){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 aw===e&&(aw=void 0),t}));aw=e}return aw}iw.logger=(0,C.h)("local-cua:rpc"),iw.serviceAppBundleName="Cursor Computer Use",iw.appSupportFolder="cursor-computer-use",iw.productionExecutableName="CUCursorService",iw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],iw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",iw.serviceAppOverrideEnv="CUA_SERVICE_APP",iw.directLaunchEnv="CUA_DIRECT_LAUNCH",iw.protocolMajor=1,iw.defaultCallTimeoutMs=45e3,iw.launchReadyTimeoutMs=8e3,iw.launchPollIntervalMs=200,iw.requestID=1;var lw=r("node:module");const uw="mac-webp-runtime.cjs";function dw(e){return"function"==typeof e}function hw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function pw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(hw):[]}let fw,mw;function gw(){return fw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=pw()[0]?.getFileName();return function(){const e=lw;if("createRequire"in e&&dw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&dw(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}})(),fw}function ww(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(mw??=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 pw()){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,Bp.fileURLToPath)(n):n);r((0,s.join)(t,uw)),r((0,s.join)(t,"..","..","src","computer-use",uw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),uw)),r((0,s.join)(process.cwd(),"src","computer-use",uw)),r((0,s.join)(process.cwd(),"computer-use",uw));try{const e=(0,s.dirname)(gw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",uw)),r((0,s.join)(e,"dist","computer-use",uw))}catch{}for(const t of e)try{const e=gw()(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")}(),mw)}function yw(...e){return t=["@jsquash","webp",...e].join("/"),gw().resolve(t);var t}async function vw(...e){var t;return await(t=(0,Bp.pathToFileURL)(yw(...e)).href,ww()(t))}const bw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Sw=(bw((async()=>{const e=await vw("decode.js");return await e.init({wasmBinary:await ti.promises.readFile(yw("codec","dec","webp_dec.wasm"))}),e})),bw((async()=>{const[e,t,r]=await Promise.all([vw("utils.js"),vw("meta.js"),vw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await ti.promises.readFile(yw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),kw="image/png",_w={async normalize(e){if(e.mimeType!==kw)throw new Error(`Mac screenshot must be ${kw}, received ${e.mimeType}`);const t=await cw(),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 Sw(),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}},Cw={userFacing:function(e){if(e instanceof rw&&e.userFacing&&e.message.trim().length>0&&!Vg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof rw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Ew=new Set(["keys"]),xw=new Set(["matched","mismatch","unchecked"]),Pw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Iw=new Set(["matched"]),Rw=new Set(["too_long"]),Tw=new Set(["watched","fell_back","unavailable","over_budget"]);class Aw{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??Cw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Aw.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:Aw.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:Aw.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:Aw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Aw.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:Aw.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===Ag.EB.DOWN||t.value.stroke===Ag.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 Ag.ks({result:{case:"success",value:new Ag.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=Aw.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=Aw.cursorFromResult(e)??Aw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Aw.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",xw),a=o("unchecked",Pw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Iw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Rw.has(a);return new Ag.qA({method:o("method",Ew)??"",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",Tw)})}async errorResult(e){let t;if(Aw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:nw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Aw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:nw(e)})}const r=this.errors.userFacing(e);return new Ag.ks({result:{case:"error",value:new Ag.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 Ag.ks({result:{case:"error",value:new Ag.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ag.ks({result:{case:"error",value:new Ag.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Aw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Aw.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=nw(r);return Aw.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 Ag.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 Ag.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()}))}}Aw.logger=(0,C.h)("local-cua:actions"),Aw.mouseButtonNames={[Ag.w3.UNSPECIFIED]:"left",[Ag.w3.LEFT]:"left",[Ag.w3.RIGHT]:"right",[Ag.w3.MIDDLE]:"middle",[Ag.w3.BACK]:"left",[Ag.w3.FORWARD]:"left"},Aw.scrollDirectionNames={[Ag.Dh.UNSPECIFIED]:"down",[Ag.Dh.UP]:"up",[Ag.Dh.DOWN]:"down",[Ag.Dh.LEFT]:"left",[Ag.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,C.h)("local-cua:windows");var $w;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"]),function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}($w||($w={}));var Mw=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 Dw{constructor(e,t,r,n,o){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o}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,i.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Er.Pi({result:{case:"error",value:new Er.GU({path:n,error:Si})}});const o=(0,bi.o1)(n,this.workspacePath),a=await this.permissionsService.shouldBlockWrite(e,o,"");if(a){const e=await hu(a,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Er.Pi({result:{case:"rejected",value:new Er.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const c=await async function(e,t){const r=await(0,Ys.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Ys.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,bi.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),l=await this.pendingDecisionProvider.requestApproval({type:$w.Delete,details:{path:c},toolCallId:t.toolCallId});if(!l.approved)return new Er.Pi({result:{case:"rejected",value:new Er.iq({path:o,reason:l.reason||""})}});let u;try{u=await(0,Ys.stat)(o)}catch(e){return"ENOENT"===el(e)?new Er.Pi({result:{case:"fileNotFound",value:new Er.n0({path:o})}}):new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:tl(e)})}})}if(!u.isFile()){const e=u.isDirectory()?"directory":"other";return new Er.Pi({result:{case:"notFile",value:new Er.LX({path:o,actualType:e})}})}const d=u.size;let h;if(d<=Ci)try{h=await sc(o)}catch{}const p=h??"",f=await(0,Ys.stat)(o).catch((()=>{}));if(f?.dev!==u.dev||f.ino!==u.ino)return new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Ys.unlink)(o)}catch(e){return"EACCES"===el(e)?new Er.Pi({result:{case:"permissionDenied",value:new Er.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===el(e)?new Er.Pi({result:{case:"fileBusy",value:new Er.vX({path:o})}}):new Er.Pi({result:{case:"error",value:new Er.GU({path:o,error:tl(e)})}})}if(this.fileChangeTracker&&void 0!==h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(o,h,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Er.Pi({result:{case:"success",value:new Er.fl({path:o,deletedFile:o,fileSize:BigInt(d),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Mw(r)}}}class Ow{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===Nt));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 ds.I0({serverIdentifier:Nt,serverName:Nt,instructions:`User-defined tools for this session (server "${Nt}"). 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 Fw extends Ow{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Nw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),jw=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 Lw{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,i.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const e=await fetch(n),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new Nw.uN({result:{case:"success",value:new Nw.Uk({url:n,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Nw.uN({result:{case:"error",value:new Nw.fk({url:n,error:tl(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{jw(r)}}}class Uw{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){const o=this.changes.get(e);if(o){const t=o.before,s=n||o.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:s};this.changes.set(e,n),this.notify(n)}}else{const o={path:e,before:t,after:r,metadata:n};this.changes.set(e,o),this.notify(o)}}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,Ys.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 cc(e,t,r,n);await(0,Ys.writeFile)(e,o),await ac(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()}}class Bw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const Ww=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),Hw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],qw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,zw=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Gw=new Set(["system","global","command"]),Vw={GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",GIT_SSH_COMMAND:"ssh -o BatchMode=yes",GCM_INTERACTIVE:"Never",GIT_EDITOR:":",GIT_SEQUENCE_EDITOR:":",GIT_OPTIONAL_LOCKS:"0",GIT_LFS_SKIP_SMUDGE:"1",GIT_CONFIG:void 0};function Kw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const Jw=Kw([...gh("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 Zw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Xw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function Qw(){const e=new Map;return{async exec(t,r,n){const o=Zw(n);return Ch("git",await Yw(e,t,r,o),{cwd:t,env:Vw,windowsHide:!0,killSignal:"SIGTERM",timeout:Xw(o)})},async run(t,r,n){const o=Zw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=kh(t);return(0,bl.spawn)("git",s,{...o,env:_h(s,n)})}(0,t,{cwd:e,env:Vw,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"})))}),Xw(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 Yw(e,t,r,o),o,n?.input)}}}async function Yw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=kh(e),r=bh(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=Ww.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=[...Hw,..."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),...Jw],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 Ch("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Vw,windowsHide:!0,killSignal:"SIGTERM",timeout:Xw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Bw("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 Bw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Bw("read-failed",t)}(e)}if(performance.now()>=r)throw new Bw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Bw("read-failed");const r=new Set;for(let e=0;eKw([[`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 ey(e,t,r){return Qw().exec(e,t,r)}var ty=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 ry{async exec(e,t,r,n){return ny(e,t,r,n,ey)}forRequest(){const e=Qw();return{exec:(t,r,n,o)=>ny(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function ny(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,i.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:a,stderr:c}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:a,stderr:c}}catch(e){s.error=e,s.hasError=!0}finally{ty(s)}}var oy=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class sy{constructor(){this.lineEnd=0,this.nextStart=0}}function iy(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 cy=-(2**31),ly=2**31-1;function uy(e){return Number.isNaN(e)?0:ely?ly:e}function dy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return uy(Math.trunc(e))}var hy=r("../mcp-core/dist/transport/mcp-url-utils.js");function py(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function fy(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function my(e,t,r){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){return!0===e.url?.startsWith("mcp-provider://")}(e))return!0;const n=t.allowedMcpServers??[];return 0===n.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){const n=r?.matchesServerUrlPattern??hy.vc;return t.some((t=>{const r=py(t.command),o=fy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,hy.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t,r)}(e,n,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){const n=r?.matchesServerUrlPattern??hy.vc;return(t??[]).some((t=>{const r=py(t.command),o=fy(t.serverUrl);if(void 0===r&&void 0===o)return!1;const s=void 0===r||void 0!==e.command&&(0,hy.mD)(r,e.command),i=void 0===o||void 0!==e.url&&n(o,e.url);return s&&i}))}(e,t.deniedMcpServers,r)}var gy=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 wy extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class yy extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class vy extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class by{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new wy(t);return await o(e,r)}}class Sy{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,i.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new yy(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{gy(s)}}}class ky{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,Js.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,Ys.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,Ys.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Ys.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var _y=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},Cy=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 Ey{async load(e,t,r,n,o){const s=o(e,r);return new Py(e,t,s,r)}}function xy(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Py{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,i.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=_y(t,(0,i.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=_y(s,(0,i.VI)(e.withName("CachedMcpClient.callTool")),!1),c=await this.getClient(a.ctx);if(null===c)throw new Error("Client is not ready");return c.callTool(a.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{Cy(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=_y(r,(0,i.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{Cy(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=xy(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{Cy(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=_y(n,(0,i.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{Cy(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=_y(t,(0,i.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{Cy(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function Iy(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ry(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 Ty(e){return e?` (${Ry(e,"")})`:""}function Ay(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=Ay(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=Ay(n);if(void 0===e)return;r[t]=e}return r}function $y(e){const t=Ay(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const My=new TextDecoder("utf-8",{fatal:!0});function Dy(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function Oy(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=My.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=Dy(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: ${Ry(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const Fy=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function Ny(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function jy(e){if(!Iy(e))return;const t=e.resource;return Iy(t)&&void 0===Ny(t)&&"string"==typeof t.blob&&Fy.has(Dy(t.mimeType))?t.blob:void 0}function Ly(e){const t=e,r=t.resource;if(Iy(r)){const e=Ny(r);return void 0!==e?e:"string"==typeof r.blob?Oy(r,r.blob).text:`Resource: ${Ry(r.uri,"unknown")}${Ty(r.name)}`}return t.uri?`Resource: ${Ry(t.uri,"unknown")}${Ty(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function Uy(e){const t=$y(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var By=r("zod/v4-mini");const Wy=By.object({CLIENT_ID:By.string(),CLIENT_SECRET:By.optional(By.string()),scopes:By.optional(By.array(By.string()))}),Hy=By.strictObject({caBundle:By.string().check(By.trim(),By.minLength(1),By.maxLength(131072))}),qy=By.object({type:By.optional(By.literal("stdio")),command:By.string(),args:By.optional(By.array(By.string())),env:By.optional(By.record(By.string(),By.string())),envFile:By.optional(By.string()),cwd:By.optional(By.string()),enabledTools:By.optional(By.array(By.string())),startupTimeoutSec:By.catch(By.optional(By.number().check(By.positive())),void 0)}),zy=By.object({type:By.optional(By.enum(["http","sse"])),url:By.string(),headers:By.optional(By.record(By.string(),By.string())),auth:By.optional(Wy),tls:By.optional(Hy),placement:By.optional(By.enum(["server","client"])),enabledTools:By.optional(By.array(By.string()))}),Gy=By.union([qy,zy]),Vy=By.object({mcpServers:By.record(By.string(),Gy)});Error;const Ky=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Jy(e,t){if("string"==typeof e)return function(e,t){return e.replace(Ky,((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=>Jy(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=Jy(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 Zy(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const Xy=Zy({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),Qy=Zy({caBundle:"ca_bundle"}),Yy=Zy({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),ev=Zy({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),tv=(new Map([["auth",{keys:Xy,unknownKeyIsError:!1}],["tls",{keys:Qy,unknownKeyIsError:!0}]]),"enabled");new Set([...Yy.jsonKeyOf.keys(),...ev.jsonKeyOf.keys(),tv]);Symbol("disabled");const rv=(0,C.h)("McpConfig");async function nv(e,t=e=>process.env[e]){try{const r=await(0,Ys.readFile)(e,"utf8"),n=Jy((0,Bd.qg)(r),t);return Vy.parse(n)}catch{return{mcpServers:{}}}}async function ov(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function sv(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await ov(0,t);return n.length>0&&rv.warn((0,ye.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 iv=["enterprise","project","user","env"];function av(e){return"project"===e||"env"===e}const cv=["0.0.0.0/0","::/0"];function lv(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,hy.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function uv(e){const t=!0===e.enabled,r=lv(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...cv];const t=lv(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...cv]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...cv];const r=(0,hy.b6)(e);return r.includes("*")?[...cv]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class dv 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 hv=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class pv extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class fv 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 mv(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function gv(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&&hv.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(!mv(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 fv;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 fv;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 pv;return e(i,a)}}function wv(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)&&xv(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=bv(e,n),s=Cv(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:bv(e,"cause"),l=Cv(c,t,r),u=e instanceof AggregateError?bv(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>Cv(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])=>vv(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(kv(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[Sv];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=Rv(e);return void 0!==g&&Rv(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 yv(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 vv(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function bv(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const Sv=Symbol.for("nodejs.util.inspect.custom");function kv(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 _v(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return wv(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>_v(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:_v(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function Cv(e,t,r){if(e instanceof Error)return wv(e,t,r);try{return xv(e,t)?_v(e,t,1,r):e}catch{return}}const Ev=4096;function xv(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=Ev||n.length>Ev)return Pv(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((Iv(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(bv(s,"message"),bv(s,"stack"),bv(s,"cause")),s instanceof AggregateError&&n.push(bv(s,"errors")));for(const e of Object.keys(s))n.push(bv(s,e))}}return!1}function Pv(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,bv(n,e)]))),message:bv(n,"message"),stack:bv(n,"stack"),cause:bv(n,"cause"),...n instanceof AggregateError?{errors:bv(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function Iv(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 Rv(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const Tv=/spt_[A-Za-z0-9_]{6,}/g,Av=/[A-Z0-9]/;function $v(e){return function(e){return e.replace(Tv,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&Av.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var Mv=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set([1,2]);const Dv="cursor/requiresConfirmation",Ov="https://grok.com/connectors-oauth-exchange-code/",Fv="https://x.com/i/connectors/oauth_callback",Nv="https://chat.x.com/connectors/oauth_callback",jv="https://lite.x.com/i/connectors/oauth_callback",Lv={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},Uv={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Ov,Fv]},Bv="x-cursor-auth";function Wv(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 Hv="https://mcp.shop.com",qv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},zv=new Map([["mcp.slack.com",{gate:"mcp_oauth_scope_step_up",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/}]]),Gv=new Map([["gmailmcp.googleapis.com",{...Lv,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",{...Lv,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Lv,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",{...Lv,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Lv,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Lv,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Lv,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",Uv],["mcp.money-staging.x.com",Uv],["mcp.money.x.com",Uv],["connectors-gateway.grok.gcp.mouseion.dev",qv],["connectors-gateway.grok.com",qv],["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.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","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:Hv}}]]),Vv=[".cloud.databricks.com",".azuredatabricks.net",".gcp.databricks.com"];const Kv=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Jv={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Zv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0};function Xv(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(".."))&&Vv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Jv:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Kv.test(e.pathname.replace(/\/+$/,""))}(t)?Zv:(r=t.hostname,Gv.get(r.toLowerCase()));var r}function Qv(e){return e.endsWith("/")?e:`${e}/`}async function Yv(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Qv(r.pathname).startsWith(Qv(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const eb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function tb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function rb(e,t){if(void 0===t)return;const r=new URL(e),n=tb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!eb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function nb(e){const t=tb(e);return void 0===t?void 0:zv.get(t.hostname.toLowerCase())}const ob=new Set([...Gv].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),sb="https://www.cursor.com/bot/mcp/oauth/callback",ib={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:sb},ab="tailnet_";new Set([`${ab}waiting_for_approval`,`${ab}tailnet_locked`,`${ab}joining`]);const cb="grokbot://mcp/oauth/callback",lb="http://localhost:8787/callback",ub="gb";new Set(["outlook","outlook-calendar","onedrive","teams"]),new Set(["teams"]);function db(e){const t=new URL(lb);return t.port=String(e),t.toString()}function hb(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 pb(e){const t=e.redirectUrl??lb;if(!0!==e.loopbackIpv4||!hb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function fb(e,t=ib){const r=new Set,n=void 0!==e&&hb(e);return e&&!n&&r.add(e),r.add(t.portal),e===cb&&r.add(t.grokBotBounce),r.add(lb),e&&n&&r.add(e),Array.from(r)}new Map([[ub,cb],["gw",Ov],["gd",lb],["xa",Fv],["xc",Nv],["xl",jv],...[18787,28787,31787].map((e=>[`gd${e}`,db(e)]))]),new Map([[cb,ub],[sb,ub],[Ov,"gw"],[Fv,"xa"],[Nv,"xc"],[jv,"xl"]]),pb({loopbackIpv4:!0}),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const mb=new Set([429,502,503,504]);function gb(e){return"object"==typeof e&&null!==e}function wb(e){const t=gb(e)?e.code:void 0,r=(e instanceof Error||gb(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&&mb.has(o)&&!mb.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}const yb=8192;function vb(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Wv(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const bb=/\$\{[^}]*\}/;function Sb(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&bb.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const kb=new Map;async function _b(e,t=fetch){if(void 0===Wv(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=kb.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 kb.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Ei.J)((function(){kb.clear()}));const Cb={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function Eb(e){return Cb}const xb=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Pb=["invalid_request","invalid_token","insufficient_scope"];function Ib(e){return Pb.some((t=>t===e))}function Rb(e){const t=[];for(const r of e){if(t.length>=20)break;r.length>0&&r.length<=200&&xb.test(r)&&!t.includes(r)&&t.push(r)}return t}const Tb=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,Ab=/"((?:[^"\\]|\\.)*)"?/y,$b=/[^\s,]*/y;function Mb(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 Fb(e){if("object"!=typeof e||null===e||Array.isArray(e))return Db;const t=Ob("grantedScopes"in e?e.grantedScopes:void 0),r=Ob("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:Ob("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:Ob("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Nb(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function jb(e,t){return e.filter((e=>!t.has(e)))}const Lb={stepUpScopes:[],recordRequestedScopes:async()=>{}};function Ub(e){const t=nb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=Eb(e.accountKey);let o;const s=async()=>Fb(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Nb(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=Mb(t,"error")?.toLowerCase(),n=Mb(t,"resource_metadata");return{error:void 0===r||""===r?"none":Ib(r)?r:"other",scopes:Rb((Mb(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 ob.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl)||!await e.isEnabled())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 Rb(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(){if(!await e.isEnabled())return Lb;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:Nb(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Fb(n),s=Nb(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=jb(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:jb(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}=Fb(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Bb(e){const t=nb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Wb(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:Bb(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 Hb extends Error{constructor(e,t,r){super(Wb({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 Wb({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function qb(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}}var zb=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Gb="2026-07-28",Vb=-32022,Kb="io.modelcontextprotocol/protocolVersion",Jb="io.modelcontextprotocol/clientCapabilities",Zb="io.modelcontextprotocol/clientInfo",Xb="io.modelcontextprotocol/serverInfo",Qb={name:"cursor",version:"1.0.0"},Yb=new Map;function eS(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tS(e){const t=new URL(String(e));return t.hash="",t.href}function rS(e,t){const r=Yb.get(e);return!(void 0===r||r<=t()&&(Yb.delete(e),1))}function nS(e,t){try{return tS(e)===t}catch{return!1}}function oS(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}function sS(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Gb),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=eS(o.params)?o.params:{},a=eS(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===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,[Kb]:Gb,[Jb]:n.capabilities,[Zb]:n.clientInfo}}});return{...e,headers:s,body:l}}function iS(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function aS(e,t){const r=tS(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Qb}},s=!1;const i=()=>s||rS(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,sS(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!oS(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!eS(n)||!eS(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Gb))return iS({id:t,error:{code:Vb,message:"Unsupported protocol version",data:{requested:Gb,supported:s??[]}}});const i=eS(o._meta)?o._meta:{},a=eS(i[Xb])?i[Xb]:{name:new URL(r).hostname,version:"unknown"};return iS({id:t,result:{protocolVersion:zb.aE,capabilities:eS(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){Yb.set(e,t()+6e5)}(r,n)),d}return e(i,sS(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!nS(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!eS(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()&&nS(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=eS(l.message.params)?l.message.params:{};o={capabilities:eS(e.capabilities)?e.capabilities:{},clientInfo:eS(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?rS(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||!oS(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(!eS(r)||!eS(r.error))return!1;const n=r.error;if(n.code!==Vb||!eS(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Gb)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function cS(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()===Bv));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()!==Bv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function lS(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(Bv,i),r(n,{...o,headers:a,redirect:"manual"})}}class uS{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=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var dS=r("crypto");function hS(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function pS(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 fS(e,t){return pS(e,t)}function mS(e){if(e)return(0,dS.createHash)("sha256").update(e).digest("hex").slice(0,12)}function gS(e){if(e&&0!==e.length)return mS(JSON.stringify([...e].sort()))}function wS(e){return{clientIdHash:mS(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:gS(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function yS(e){return"object"==typeof e&&null!==e}function vS(e,t){let r=e;for(const e of t){if(!yS(r)||!(e in r))return;r=r[e]}return r}function bS(e,t){for(const r of t){const t=vS(e,r.split("."));if("string"==typeof t)return t}}function SS(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function kS(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 _S=e=>e;function CS(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?AS(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?AS(t(r)):void 0}}function ES(e){if(e&&"object"==typeof e)return yS(e)?e.cause:void 0}function xS(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const PS="[REDACTED]",IS=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function RS(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${PS}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${PS}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${PS}`)}function TS(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function AS(e,t){return TS(RS(e),t?.maxLength)}function $S(e,t=_S){if("string"==typeof e)return TS(RS(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")||IS.test(t)}(e)?PS:"string"==typeof r?RS(t(r)):r));if(!r)return;return TS(r)}catch{return}}function MS(e,t=_S){const r=ES(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=CS(r,t),i=CS(e,t)??s,a=bS(e,["code","cause.code"]),c=SS(e)??SS(r)??bS(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:AS(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=vS(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??kS(i)??kS(s),d=$S(vS(e,["response","body"])??vS(e,["body"])??vS(e,["data"])??vS(e,["cause","body"])??vS(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 hS({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:xS(e,t),sdkErrorKind:p})}const DS={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 OS(e){const t=e.message??DS[e.event],r={event:e.event,cursorMcp:{oauth:hS({...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 FS=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]))),NS=4096;function jS(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function LS(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function US(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function BS(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(US(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function WS(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function HS(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function qS(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:HS(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:HS(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:HS(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:HS(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:HS(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:HS(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:HS(t.get("content-length"))}}function zS(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 GS(e){const{input:t,init:r}=e,n=pS(LS(t)),o=function(e,t){const r=new Headers(BS(jS(e)?e.headers:void 0));return new Headers(BS(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=WS(o),i=o.get("content-type"),a=mS(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return FS.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(jS(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:qS(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function VS(e,t){const r=WS(e.headers),n=HS(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:mS(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:mS(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:KS(e.headers,"retry-after"),slackRateLimitType:KS(e.headers,"x-slack-ratelimit-type")}}function KS(e,t){return e.get(t)?.slice(0,64)??null}function JS(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 ZS(e,t){const r=GS({input:e,init:t});if(void 0!==zS(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 XS=e=>e;async function QS(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function YS(e){if(!ZS(e.input,e.init))return;const t=await QS(e.response,NS,e.redact);if(void 0!==t)try{return $S(JSON.parse(t))}catch{return AS(t,{maxLength:NS})}}async function ek(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 QS(t,NS,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=pS(LS(e.input)).path)&&!0!==t?.endsWith("/mcp"))return AS(e.rawText,{maxLength:NS});var t;try{const t=JSON.parse(e.rawText);return US(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!US(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?AS(r.message,{maxLength:NS}):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 YS({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function tk(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function rk(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=>rk(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,rk(n,t,r+1)])))}function nk(e,t){const r=e=>{const r=rk(e,t,0);return US(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 ok(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:nk(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await ek({input:s,init:i,response:e,redact:n??XS});return!r&&e.ok||tk((()=>{!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=GS({input:t,init:r}),l=zS(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:VS(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")&&!ZS(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:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!yS(e))return;const t=yS(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}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await ek({input:s,init:i,response:t,redact:n??XS}):{};throw tk((()=>{!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=MS(n,e.redactLogText),u=GS({input:t,init:r}),d=zS(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?VS(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:JS(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}Error,Error;const sk=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),ik=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),ak=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];function ck(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}}const lk=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],uk=[".exe",".cmd",".bat"],dk=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,hk=new Set(["py","pyw"]),pk=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),fk=new Set;function mk(e){return lk.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 gk(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of uk)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(dk.test(r)||hk.has(r)||"uvx"===r)return!0;if("uv"===r){const e=gk(t,pk);return"run"===e?.value||"tool"===e?.value&&"run"===gk(e.rest,pk)?.value}return"pipx"===r&&"run"===gk(t,fk)?.value}(n,o)?mk(i)||mk(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function yk(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 vk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),bk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Sk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),kk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),_k=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");function Ck(e){return`${typeof e}:${String(e)}`}function Ek(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(Ck(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Ck(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=Ck(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 xk(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,Js.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Pk{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,zb.vo)(e)&&(0,zb.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,zb.wU)(e)||await this.inner.send(e,t)}}const Ik=Nn.object({tools:Nn.array(Nn.unknown()),nextCursor:Nn.unknown().optional()}),Rk={typeFilled:0,toolDropped:0,outputStripped:0};function Tk(e){if(Fk(e))return"string"==typeof e.name?e.name:void 0}function Ak(e){return $k(e.issues.filter((e=>"outputSchema"===e.path[0])))}function $k(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function Mk(e){if(!Fk(e))return e;const t={...e};return delete t.outputSchema,t}function Dk(e){return Fk(e)&&!("type"in e)}function Ok(e,t){return{...e,inputSchema:{type:"object",...t}}}function Fk(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Nk=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const jk=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Nk.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,Js.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 Lk{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>=yb}append(e){const t=yb-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}=yi(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:vb(t),...r}))}catch{}}const Gk=(0,E.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 Vk(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Kk=["authorization_code","refresh_token"],Jk=["code"];class Zk{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=tb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(Hv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?rb:Yv}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled??(()=>!1),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,Js.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=()=>!1){const n=Xv(e);if(!0!==n?.pinsScopesOverConfiguredScopes){if(void 0!==t&&t.length>0)return t;const n=nb(e);return void 0!==n&&r(n.gate)?n.baseScopes:t}return void 0===n.scopesPinGate||r(n.scopesPinGate)?n.scopes??t:t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=Xv(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 Xk(e){const{serverName:t,config:n,tokenStorage:o}=e,{isScopeChallengeStepUpEnabled:s}=e,i=await _b(n.url,e.fetchImpl),a=pb({loopbackIpv4:i?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),c=function(e,t){const r=Sb(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:fb(t),grant_types:[...Kk],response_types:[...Jk],token_endpoint_auth_method:"none"}}(n.auth,a),l=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:c});return new Zk({identifier:t,redirectUrl:a,serverUrl:n.url,restMcpProviderMetadata:i,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:fb(a),token_endpoint_auth_method:"none",grant_types:[...Kk],response_types:[...Jk],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...void 0!==s&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Ub({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),isEnabled:async()=>s(),readScopesSupported:t=>async function(e){try{const{discoverOAuthProtectedResourceMetadata:t}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"));return(await t(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch)).scopes_supported}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:l,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:l?.client_id})})}const Qk=new Set;let Yk=!1;function e_(){for(const e of Qk)try{process.kill(e,"SIGKILL")}catch{}}function t_(e,t){return aS(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function r_(e,t,r){const n=cS(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?lS((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class n_{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 uS,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}})();OS({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(){return new bk.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}},extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}},jsonSchemaValidator:jk})}setupElicitationHandler(){this.client.setRequestHandler(zb.$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){const d=new URL(t.url);o=o??lb;const h=await Xk({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,isScopeChallengeStepUpEnabled:u}),p=h.tokens(),f=cS(t.url,n),m=f.headers,g=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),w=void 0!==f.cursorAuthHeaderValue&&void 0!==f.cursorAuthOrigin&&void 0!==g?lS((()=>f.cursorAuthHeaderValue),f.cursorAuthOrigin,g):g,y=e=>void 0===w||void 0===i?w:ok({fetch:w,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let v;const b=e=>{const r=h.scopeStepUp,n=e??g;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,vk.j2)(h,{serverUrl:d.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==w?{fetchFn:w}:{}});const r=h.lastRedirectUrl;v=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:qb(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){Eb(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 Hb(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},S=n_.createClient(),k=e=>e instanceof vk.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&sk.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!ik.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&&ak.some((e=>e.test(n)))}(e)}(e),_=async t=>{if(!h.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!==v&&v.redirectUrl===h.lastRedirectUrl?v.resourceMetadataUrl:void 0;await(0,vk.j2)(h,{serverUrl:d.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==w?{fetchFn:w}:{}}),a&&OS({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...fS(d.toString()),...ck(h.tokens(),{expiresInIsFresh:!0})}})},C=r=>{const n=h.lastRedirectUrl?.toString?.()??"",o=new n_(e,S,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await _(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:h,authCodeExchange:_,sessionId:r,config:t});return o},E=async()=>{const r=new Sk.A(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(y("sse"))});try{return await S.connect(r),new n_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await r.close().catch((()=>{})),k(t))return a&&OS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(p?.refresh_token),...fS(d.toString()),...MS(t,i?.redactLogText)}}),C();throw t}};if("sse"===t.type)return E();const x=new _k.j(d,{authProvider:h,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...m??{}}},fetch:b(t_(y("streamableHttp"),d))});try{await S.connect(x);const r=function(e,t=Date.now){return rS(tS(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:xk({url:t.url,headers:n,accessToken:h.tokens()?.access_token})}}(S,x);return new n_(e,S,{initialState:{kind:"ready"},authProvider:h,authCodeExchange:_,sessionId:x.sessionId,protocolVersion:x.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(k(t))return a&&OS({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(p?.refresh_token),...fS(d.toString()),...MS(t,i?.redactLogText)}}),C(x.sessionId);if(function(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)}(t))return E();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=n_.createClient(),o=new _k.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new n_(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=lb,i,a,c,l,u){const d=new URL(t.url),h=await Xk({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=r_(t.url,o,i),m=new _k.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ok({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=n_.createClient();return await g.connect(m),new n_(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=lb,i,a,c,l){const u=await Xk({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(xk({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=r_(t.url,o,i),p=new _k.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=n_.createClient();return await f.connect(new Pk(p,r.result)),new n_(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 _k.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{Bk(s,(0,i.VI)(e.withName("McpSdkClient.fromCommand")),!1);const u=(l=o?.spawn,void 0!==l||"linux"!==process.platform?l:(e,t,r)=>(0,Sl.D9)(bl.spawn,e,t,r)),d=r.args??[],h=new kk.oQ({command:r.command,args:d,env:wk({command:r.command,args:d,env:n}),cwd:r.cwd,stderr:"pipe",...u&&{spawn:u}}),p=function(e){const t=new Lk;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>AS(t.text.replace(/\s+/g," ").trim(),{maxLength:yb}),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)}))}}}(h.stderr),f=n_.createClient(),m=o?.connectTimeoutMs??(void 0!==(c=r.startupTimeoutSec)&&Number.isFinite(c)&&c>0?Math.min(1e3*c,3e5):6e4);let g;h.onclose=()=>{var e;void 0!==g&&(e=g,Qk.delete(e))};const w=new AbortController,y=f.connect(h,{timeout:m,signal:w.signal});let v;g=h.pid??void 0,void 0!==g&&(a=g,Qk.add(a),Yk||(Yk=!0,process.on("exit",e_)));const b=new Promise(((e,r)=>{v=setTimeout((()=>r(new Error(`MCP server connection timed out after ${m}ms: ${t}`))),m)}));try{await Promise.race([y,b])}catch(e){throw w.abort(),y.catch((()=>{})),await h.close().catch((()=>{})),await p.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Uk.set(r,t),r}(e,p.read())}finally{void 0!==v&&clearTimeout(v)}return new n_(t,f,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==g,serverSignals:Ek(h)})}catch(e){s.error=e,s.hasError=!0}finally{Wk(s)}var a,c,l}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 _k.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 _k.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=Bk(t,(0,i.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Vk(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()=>{const e=await yk({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...Rk}}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}},Ik),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(Fk(e)){const r=e.inputSchema;Dk(r)&&(t=Ok(e,r),s++)}let n=zb.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=zb.Dn.safeParse(Mk(t));o.success&&(a++,r(Tk(e),Ak(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Tk(e),$k(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(s_.has(n))return s_.delete(n),s_.add(n),!1;if(s_.add(n),s_.size>256){const e=s_.keys().next().value;void 0!==e&&s_.delete(e)}return!0})(n,this.serverName,e??"")&&Hk.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+=t.typeFilled,i_(r.ctx,"type_filled",t.typeFilled),i_(r.ctx,"tool_dropped",t.toolDropped),i_(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:Ay(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:Ay(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){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,e,n),e instanceof vk.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const t=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(t,this.stateValue,"runtime_unauthorized",{...MS(e,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}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=zb.O4.MethodNotFound;if(t instanceof zb.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof vk.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof zb.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof _k.b||e instanceof Sk._){const t=e instanceof _k.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&&Hk.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 c=Bk(s,(0,i.VI)(e.withName("McpSdkClient.callTool")),!1);c.span.setAttribute("toolName",t),c.span.setAttribute("serverName",this.serverName),c.span.setAttribute("mcp.transport",Vk(this.config));const l=this._callToolLock,u=this._callToolQueueDepth;let d;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{d=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=Bk(e,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",u);const r=performance.now();await l;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),c.span.setAttribute("mcp.call_tool.lock_wait_ms",n),c.span.setAttribute("mcp.call_tool.queued_ahead",u)}catch(t){e.error=t,e.hasError=!0}finally{Wk(e)}}if("requires_authentication"===this.stateValue.kind)throw new vk.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const d=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=Bk(n,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const l=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===l.isError),zk(e,this.config,{isError:!0===l.isError}),{content:l.content,isError:!0===l.isError,structuredContent:(a=l.structuredContent,$y(a)),_meta:Uy(l._meta)}}catch(e){n.error=e,n.hasError=!0}finally{Wk(n)}}catch(t){t instanceof Hb?(zk(e,this.config,{error:t,httpStatus:t.decision.status}),function(e,t){try{Gk.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,t)):zk(e,this.config,{error:t});const r=t instanceof Hb&&"offer"===t.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==d;if((t instanceof vk.D_||r)&&"ready"===this.stateValue.kind){const e=this.stateValue,n=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:n,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,r?"scope_step_up":"runtime_unauthorized",{...MS(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,l.then(d)}}catch(e){s.error=e,s.hasError=!0}finally{Wk(s)}var a}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},zb.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(Bk(t,(0,i.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{Wk(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(Bk(t,(0,i.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 yk({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{Wk(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return Bk(r,(0,i.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{Wk(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return Bk(t,(0,i.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await yk({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{Wk(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return Bk(n,(0,i.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{Wk(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 o_=(0,E.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),s_=new Set;function i_(e,t,r){if(0!==r)try{o_.increment(e,r,{outcome:t})}catch{}}class a_ 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 c_{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new Xt(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class l_{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new c_({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class u_{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=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{Wk(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 d_{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=Bk(t,(0,i.VI)(e.withName("McpManager.getToolSet")),!1),n=Bk(t,h_(this.listingDeadlineAt),!1),o=await(0,or.PH)(Object.entries(this.clients),(([e,t])=>n.within(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(),a=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=a.get(t);void 0===r?a.set(t,[e]):r.push(e)}const c={};for(const[e,t]of a){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}`)),c[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},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 c_(c)}catch(e){t.error=e,t.hasError=!0}finally{Wk(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bk(t,(0,i.VI)(e.withName("McpManager.getInstructions")),!1),n=Bk(t,h_(this.listingDeadlineAt),!1),o=await(0,or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t.getInstructions(r.ctx)).then((e=>e&&0!==e.trim().length?new ds.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{Wk(t)}}}function h_(e){if(void 0===e)return{concurrency:4,within:e=>e,[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:e=>Promise.race([e,r]),[Symbol.dispose]:()=>clearTimeout(t)}}function p_(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 f_{constructor(e){this.options=e,OS({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:fS(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return OS({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...ck(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),OS({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...ck(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){OS({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){OS({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...MS(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return OS({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...wS(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),OS({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...wS(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(OS({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 m_{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 g_{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 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},y_=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_=(0,C.h)("DefinitionMcpLoader");function b_(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 S_(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function k_(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function __(e){return e?.length??0}function C_(e){if(void 0!==e)return(0,Js.createHash)("sha256").update(uv(e)).digest("hex")}function E_(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?$v(r):r)}async function x_(e,t,n,o,s={middlewares:[],configPath:""},a,c,l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=w_(u,(0,i.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);let f=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=w_(s,(0,i.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(k_);return await async function(e,t,n,o){const s=n.cwd?b_({filePath:n.cwd}):void 0;let i,a;if(n.args&&n.args.length>0)i=b_({filePath:n.command,baseDir:s}),a=n.args.map((e=>b_({filePath:e,baseDir:s})));else{const e=(0,Mv.A)(n.command);i=b_({filePath:e[0],baseDir:s}),a=e.slice(1).map((e=>b_({filePath:e,baseDir:s})))}const c=n.env??{},{startupTimeoutSec:l}=n,u=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),d=(0,hy.$H)(u);if(void 0!==d){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:h}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),p=s??process.cwd(),f=await n(d,p);v_.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=${__(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${__(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${__(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${C_(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:__(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:__(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:__(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:C_(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}));try{return await n_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c,{spawn:(e,t,r)=>h(e,t,r,f)})}catch(e){if(e instanceof o)throw new dv(t,e);throw e}}return!0===u?.enabled&&"no_sandbox"===u.mcpNetworkMode&&(!0===u.win32UserExtensionUnsandbox?v_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):v_.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),n_.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c)}(h,t,n,e)}if("url"in n){u.span.setAttribute("kind","url");const e=a?.(t);return await async function(e,t,r,n,o,s,i,a){const c=p_(e,v_),l=function(e,t,r){return{logger:{debug:(t,r)=>v_.debug(e,t,r),info:(t,r)=>v_.info(e,t,r),warn:(t,r)=>v_.warn(e,t,r),error:(t,r,n)=>v_.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:E_(r)}}(e,t,a),u=void 0!==s&&mv(r.url)?gv(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return n_.fromStreamableHttp(t,r,n,r.headers,o,u,l,c,void 0,void 0,i)}(h,t,n,o,e,d.find(S_),c,l.isLinkSharedPaymentTokenLogRedactionEnabled)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{y_(s)}};for(const e of d){const r=f;f=async(n,o)=>await e.load(n,t,o,h,r)}try{return await f(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=Uk.get(e);void 0!==r&&Uk.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=wv(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 I_{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{w_(r,(0,i.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=E_(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Uk.get(e)}(r);v_.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 d_(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{y_(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(k_);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,uv(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(v_.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{w_(n,(0,i.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 a;try{a=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,a),a}catch(e){n.error=e,n.hasError=!0}finally{y_(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new m_(this.tokenStorage,n),s=p_(e,v_),i=new f_({inner:o,logger:s,redactLogText:E_(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new g_(i):i;return x_(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.isScopeChallengeStepUpEnabled,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){v_.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 wy||e instanceof yy||e instanceof vy||e instanceof R_}(r)}}class R_ 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 T_=[1e3,3e3];class A_{constructor(e){this.blockingService=e}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={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked)throw new R_(t,i.reason??"teamPolicy",i.message);for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),t}catch(e){if(e instanceof pv)throw new R_(t,"teamPolicy",e.message);const r=e instanceof fv?T_[n]:void 0;if(void 0===r)throw e;await(0,or.cb)(r)}}}class $_ extends I_{constructor(e,t,r=[],n={}){super(new P_(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new $_(t,e,r)}}function M_(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 D_=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=1b3c1ae3861bcf6cb10d777e514533bdda03fb5a607_5cdbb28abebea45d2ea06568a022aa4a/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function O_(e){const t=D_.VE.safeParse(e);return t.success?t.data:void 0}function F_(e){const t=D_.H5.safeParse(e);return t.success?t.data:void 0}class N_{constructor(e){this.mcpAuthPath=e;const t=N_.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,N_.mcpAuthPromises.set(e,t),t.catch((()=>{N_.mcpAuthPromises.get(e)===t&&N_.mcpAuthPromises.delete(e)}))}N_.saveLocks.has(e)||N_.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,Ys.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=O_(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?O_(n.tokens):void 0,clientInfo:"clientInfo"in n?F_(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=N_.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;N_.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,Ys.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,Ys.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}N_.mcpAuthPromises=new Map,N_.saveLocks=new Map;const j_=Buffer.from([137,80,78,71,13,10,26,10]),L_=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),U_=e=>{if(e.lengthe.subarray(e.length-L_.length).equals(L_)||(e=>{let t=j_.length+25;for(;t+L_.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-L_.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+L_.length).equals(L_);t+=L_.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)}},B_=e=>1===e||e>=208&&e<=216,W_=e=>192===e||193===e||194===e,H_=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,q_=e=>0===e||e>=208&&e<=215,z_=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=U_(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(B_(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=z_(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(B_(r)){t+=2;continue}if(218===r||217===r||H_(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(W_(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),V_=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),K_=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,j_.length).equals(j_)?"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},Z_={0:1,2:3,4:2,6:4},X_=({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}`)}}},Q_=({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)},eC={0:1,2:3,3:1,4:2,6:4},tC=[1,2,4,8,16],rC=[[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]],nC=async e=>{const t=oC(e);if(void 0===t)return;const r=sC(t);let n=0;const o=nh.Readable.from(t.idat).pipe((0,sh.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`)},oC=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=eC[i[9]];if(void 0===e||!tC.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}},sC=({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?rC.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const iC=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},aC=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),cC=e=>{if(!aC(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)}}},lC=e=>iC().decode(e),uC=e=>iC().encode(e);async function dC(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);G_(e.data);return e.resizeWithoutBudget(e.data)}const hC=[{width:1280,height:800},{width:1456,height:840}],pC=1048576,fC=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function mC(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 gC=(e,t,r=1024)=>mC(e,t,r),wC=(e,t,r)=>{e.resize({w:t,h:r})},yC=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`)},vC=(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:yC(((e,t)=>{switch(t){case"png":return(e=>{let t,r=j_.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=V_(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))}};const bC=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return dC({data:e,budgetBytes:r,maxImageBytes:pC,fitImage:mC,resizeWithoutBudget:e=>bC(e,n)})}if(aC(e))return(async(e,t)=>{const r=cC(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:fC(e),mimeType:"image/webp"};const n=void 0!==r&&hC.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!gC(r.width,r.height,1280).needsResize)&&e.length<=pC)return{data:fC(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:fC(e),mimeType:"image/webp"};yC(r);const o=await lC(e),s=(await cw()).fromBitmap({data:Buffer.from(o.data),width:o.width,height:o.height});let{width:i,height:a,needsResize:c}=n?{width:s.bitmap.width,height:s.bitmap.height,needsResize:!1}:gC(s.bitmap.width,s.bitmap.height,1280);c&&wC(s,i,a);let l=await uC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});for(;l.length>pC&&i>8&&a>8;)i=Math.max(8,Math.round(.8*i)),a=Math.max(8,Math.round(.8*a)),wC(s,i,a),l=await uC({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});return{data:fC(l),mimeType:"image/webp",reencoded:!0}})(e,t);const r=G_(e);if(void 0!==r&&e.length<=pC&&!gC(r.width,r.height).needsResize)return{data:fC(e),mimeType:r.mimeType};const n=J_(e);void 0!==n&&vC(e,n),"png"===n&&await nC(e);const o=await cw(),s=void 0===r?void 0:gC(r.width,r.height),i="image/png"===r?.mimeType&&!0===s?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(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=Z_[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}})(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{})):void 0,a=void 0===i?await o.read(e):o.fromBitmap(i),c=(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"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=gC(a.width,a.height);if(void 0===i&&!h&&e.length<=pC&&l===c)return{data:fC(e),mimeType:c};let p=u,f=d;h&&wC(a,p,f);let m=await a.getBuffer(l);for(;m.length>pC&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),wC(a,p,f),m=await a.getBuffer(l);return{data:fC(m),mimeType:l,reencoded:!0}},SC=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=J_(t);let n;if(aC(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{vC(t,r);const e=await cw();n=async()=>("png"===r&&await nC(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}};function kC(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 _C(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=fi(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?.[Dv]}(e)&&(t[Dv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}var CC=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},EC=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 xC=(0,E.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),PC=(0,E.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),IC=(0,E.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),RC=(0,E.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),TC=(0,E.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"]}),AC=(0,E.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"]}),$C=(0,C.h)("McpFileSystemWriter"),MC="mcpFsStructuredLogOptIn";function DC(e,t){return t?.includeStructuredLogs?{...e??{},[MC]:!0}:e}const OC={debug(e,t,r,n){$C.debug(e,t,DC(r,n))},info(e,t,r,n){$C.info(e,t,DC(r,n))},warn(e,t,r,n){$C.warn(e,t,DC(r,n))},error(e,t,r,n,o){$C.error(e,t,r,DC(n,o))}},FC="mcps",NC="tools",jC="~staging",LC="~prev",UC="mcp_auth",BC="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.",WC="# >>> CURSOR MANAGED BLOCK >>>",HC="# <<< CURSOR MANAGED BLOCK <<<",qC=["# 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 zC(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function GC(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function VC(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function KC(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 JC(e){if(Array.isArray(e))return e.map((e=>JC(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,JC(t)]));return Object.fromEntries(t)}return e}function ZC(e){return JSON.stringify(JC(e))}function XC(e){const t=e.map((e=>({value:e,key:ZC(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function QC(e){const t=XC(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=XC(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=XC(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return ZC({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 YC{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=>{OC.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),OC.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=`${WC}\n${qC}\n${HC}\n`;let n;await(0,Ys.mkdir)(e,{recursive:!0});try{n=await(0,Ys.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==el(e))throw e}if(void 0===n)return void await(0,Ys.writeFile)(t,r);const o=n.indexOf(WC),i=n.indexOf(HC,o+30);if(-1===o||-1===i)await(0,Ys.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Ys.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{OC.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,FC);try{const e=await(0,Ys.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(jC))).map((e=>(0,Ys.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==el(e)&&OC.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:qt(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:qt(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){OC.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,ye.q6)();return e&&(t=t.with(C._O,e)),t}getLogContext(e){return e.with(C._O,this.ctx.get(C._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return VC(this.mcpAuthCopyOverrides?.authToolDescription)??BC}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Lt(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return VC(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=VC(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:UC},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Lt(e)?this.getNeedsAuthStatusMessage(e):VC(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){OC.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${tl(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(OC.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 zC(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||OC.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?zC(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?zC(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?zC(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:KC(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=cE(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,FC,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=cE(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,FC,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===UC))||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:UC,name:UC,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)?OC.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):OC.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===UC))){const t=e.tools.find((e=>e.toolName===UC));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??[])];OC.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=>(OC.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 OC.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${tl(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=>{OC.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):OC.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)),OC.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=cE(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{CC(r,(0,i.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!qt(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=>(OC.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(OC.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);OC.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){OC.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{EC(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,NC,`${GC(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{CC(n,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),a=(0,s.join)(this.projectDir,FC);await(0,Ys.mkdir)(a,{recursive:!0});const c=new Map;for(const e of t)try{c.set(e.serverIdentifier,QC(e))}catch(t){OC.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),c.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==c.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&OC.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,Ys.stat)((0,s.join)(a,e.sanitizedId))}catch{OC.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!c.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??cE(e);r.has(n)?(OC.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),c.set(e,this.cachedFingerprints.get(e))):(OC.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),u.add(n))}const d=void 0===this.cachedServerData;if(d)try{const e=await(0,Ys.readdir)(a),t=new Set(e.filter((e=>!e.endsWith(jC)&&!e.endsWith(LC))));for(const r of e)if(r.endsWith(jC))await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else if(r.endsWith(LC)){const e=r.slice(0,-5);if(t.has(e))await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else try{await(0,Ys.rename)((0,s.join)(a,r),(0,s.join)(a,e)),t.add(e)}catch{await(0,Ys.rm)((0,s.join)(a,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);c.has(t)||c.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){OC.error(o,"Error clearing mcps directory",e)}const h=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));OC.info(o,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:h,unchangedServerCount:t.length-l.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:d,projectDirHash:(0,Js.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const p=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,a))));for(let t=0;t(0,Ys.rm)((0,s.join)(a,e),{recursive:!0,force:!0}))));for(let r=0;r{}))}catch(e){n.error=e,n.hasError=!0}finally{EC(n)}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{CC(n,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,Ys.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,NC);await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=GC(r.toolName),n=(0,s.join)(e,`${t}.json`),o=Wt(r);await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=GC(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Ys.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=GC(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,Ys.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,Ys.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,Ys.writeFile)(e,r)}const a=(0,s.join)(o,"SERVER_METADATA.json"),c={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,Ys.writeFile)(a,JSON.stringify(c,null,2))}catch(e){n.error=e,n.hasError=!0}finally{EC(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;CC(r,(0,i.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&&OC.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const a=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=GC(t.toolName),n=(0,s.join)(e.folderPath,NC,`${r}.json`);return new ds.E$({toolName:t.toolName,definitionPath:n,..._C(t.annotations)})}));return new ds.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,a,"workbench_lease"),new ds.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){r.error=e,r.hasError=!0}finally{EC(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&&OC.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){OC.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&OC.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){OC.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{CC(t,(0,i.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),a=(0,s.join)(this.projectDir,FC),c=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=cE(e.serverIdentifier),r=(0,s.join)(a,t),n=e.tools.map((e=>{const t=GC(e.name);return new ds.E$({toolName:e.name,definitionPath:(0,s.join)(r,NC,`${t}.json`),..._C(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===UC))){const e=GC(UC);n.push(new ds.E$({toolName:UC,definitionPath:(0,s.join)(r,NC,`${e}.json`)}))}return new ds.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})})),l=c.reduce(((e,t)=>e+t.tools.length),0);return OC.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${c.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,c,"snapshot"),new ds.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:c})}catch(e){t.error=e,t.hasError=!0}finally{EC(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{OC.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,FC),i=new Set,a=new Map;for(const e of t){const t=cE(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Ys.readdir)(o),c=c.filter((e=>!e.endsWith(jC)&&!e.endsWith(LC)))}catch(e){if("ENOENT"!==el(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++,xC.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),OC.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++,xC.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,NC);let h=0;try{h=(await(0,Ys.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,xC.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),OC.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}))}PC.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),IC.gauge(e,i.size,this.getMetricTags({mcp_source:r})),RC.gauge(e,l.size,this.getMetricTags({mcp_source:r})),TC.gauge(e,d,this.getMetricTags({mcp_source:r})),AC.gauge(e,p,this.getMetricTags({mcp_source:r})),OC.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||OC.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())}}YC.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var eE=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},tE=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 rE(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 nE=(0,C.h)("local-exec:mcp");function oE(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function sE(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function iE(e){return new er._Z({content:{case:"image",value:new er.do({data:e.data,mimeType:e.mimeType})}})}function aE(e){return new er._Z({content:{case:"text",value:new er.zN({text:e})}})}function cE(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 lE(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client}});if(!n)return;const o=await hu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new er.iz({result:{case:"error",value:new er.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:$w.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 er.iz({result:{case:"approved",value:new er.Ke}}):null:new er.iz({result:{case:"rejected",value:new er.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new er.iz({result:{case:"error",value:new er.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class uE{constructor(e,t,r,n,o=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}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}}(zt(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=eE(r,(0,i.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,a=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[a]));const c=await this.toolSet.getTools(o),l=Array.from(new Set(c.map((e=>e.clientKey)))).sort(),u=c.find((e=>e.clientKey===a&&e.toolName===t.toolName)),d=c.find((e=>e.name===t.name));if(void 0!==d&&(void 0!==u?d!==u:d.toolName!==t.toolName||d.clientKey!==a&&d.providerIdentifier!==a))return new er.iz({result:{case:"error",value:new er.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${a}" that the call names.`})}});const h=void 0===u?void 0:await this.toolSet.getClient(o,u.clientKey).catch((()=>{})),p=await lE(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u,...void 0===h?{}:{client:h}});if(void 0!==p)return p;const f=await this.toolSet.getToolSet(o);let m;try{m=await f.execute(u?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(Qt(r)&&t.providerIdentifier.length>0&&!c.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new a_(t.providerIdentifier,l)),r instanceof a_){const e=await this.describeDisconnectedServer(o,[a,t.providerIdentifier]);return void 0!==e?new er.iz({result:{case:"error",value:new er.Nh({error:e})}}):new er.iz({result:{case:"serverNotFound",value:new er.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Qt(r))return new er.iz({result:{case:"toolNotFound",value:new er.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const g=[];for(const e of m.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)g.push(aE(e.text));else if("resource"===r){const r=jy(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await bC(n).then(iE,(e=>{nE.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));g.push(s??aE(Ly(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 bC(s)}catch(e){nE.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)}),g.push(aE(`[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}g.push(iE(i))}else if("image"!==r){const t=Ly(e);g.push(aE(t))}}const w=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 er._Z({content:{case:"text",value:new er.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:g,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.default.join(t,pl),n=s.default.join(r,`${(0,Js.randomUUID)()}.txt`);await(0,Ys.mkdir)(s.default.dirname(n),{recursive:!0});const o=fi(e,fl),i=ma(o),a=Buffer.byteLength(o,"utf8");return await(0,Ys.writeFile)(n,o,"utf8"),new yl.pV({filePath:n,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===w)throw new Error("Failed to materialize MCP text output");const y=m.structuredContent&&"object"==typeof m.structuredContent&&!Array.isArray(m.structuredContent)?sr.Struct.fromJson(m.structuredContent):void 0,v=new er.QW({content:w,isError:m.isError,structuredContent:y,resultMeta:void 0===m._meta?void 0:sr.Struct.fromJson(m._meta)});return new er.iz({result:{case:"success",value:v}})}catch(e){r.error=e,r.hasError=!0}finally{tE(r)}var n}}class dE{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=eE(r,(0,i.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 er.kP({result:{case:"error",value:new er.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new er.kP({result:{case:"success",value:new er.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 er.kP({result:{case:"success",value:new er.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new er.kP({result:{case:"error",value:new er.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{tE(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 er.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:rE(e.annotations)}))):[]}}class hE{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Mt),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=eE(r,(0,i.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:$w.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:sr.Value.fromJson(t.server),uri:sr.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:sr.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new er.ZD({result:{case:"rejected",value:new er.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const a=await this.mcpLease.getClients(n),c=a[t.server]??Object.values(a).find((e=>e.serverName===t.server));if(!c)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await c.getState(n)).kind)return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await c.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new er.ZD({result:{case:"notFound",value:new er.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,Ys.realpath)(r),o=s.default.resolve(r,t.replace(/^\/+/,""));if(!oE(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.default.dirname(o);for(;;)try{if(!oE(n,await(0,Ys.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==sE(e))throw e;const t=s.default.dirname(i);if(t===i)throw e;i=t}if(await(0,Ys.mkdir)(s.default.dirname(o),{recursive:!0}),!oE(n,await(0,Ys.realpath)(s.default.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,Ys.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==sE(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,Ys.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,Ys.writeFile)(e,t)}return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:rE(r.annotations),metaJson:Bt(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new er.ZD({result:{case:"success",value:new er.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:rE(r.annotations),metaJson:Bt(r._meta),content:{case:"blob",value:e}})}})}return new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return nE.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new er.ZD({result:{case:"error",value:new er.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{tE(r)}}}async function pE(e,t){const r=cE(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Ys.readdir)(n)}catch(e){if("ENOENT"===el(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,Ys.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 fE=(0,C.h)("local-exec:mcp-disk-freshness-on-access"),mE="/mcps/",gE=(0,E.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),wE=(0,E.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),yE=(0,E.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),vE=(0,E.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),bE=new Map;function SE(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function kE({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 fE.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>cE(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void fE.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"};gE.increment(e,1,{...l,outcome:c}),wE.histogram(e,i.length,l),yE.histogram(e,a.length,l),vE.histogram(e,i.length+a.length,l),"mismatch"===c&&fE.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 _E(e,t,r,n=pE){if(void 0===r||(void 0===(o=r)||!SE(o).includes(mE)))return;var o;const s=function(e){const t=SE(e),r=t.indexOf(mE);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=bE.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{bE.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=cE(r.serverIdentifier);await kE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await kE({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{fE.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);bE.set(i,d)}async function CE(e){try{return(await(0,Ys.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function EE(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 xE(e,t,r=CE){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:EE(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}const PE=BigInt(0),IE=BigInt(8),RE=BigInt(16),TE=BigInt(65535);function AE(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function $E(e){const t=e.split(".");if(4!==t.length)return;let r=PE;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<>RE&TE)),t.push(Number(o.value&TE))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function DE(e){return $E(e)??function(e){const t=AE(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=ME(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 FE(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=>OE(e,t)))}(r.hostname,t)}function NE(e){return e.trim().toLowerCase()}function jE(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function LE({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":NE(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(NE).filter((e=>e.length>0)),n=void 0===e?void 0:NE(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:jE(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}const UE=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function BE(e){return e.trim().split(/\s+/).filter(Boolean)}function WE(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 BE(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return UE.has(n)}function HE(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=HE(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(zE(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(zE(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(zE(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const VE=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],KE=["cursor","molten glass"];function JE(e){return VE.some((t=>e===t||e.startsWith(`${t}.`)))}const ZE=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],XE=[{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"},...ZE,{bundleId:VE[0],name:"Cursor"}];function QE(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=XE.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}:JE(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>KE.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:VE[0],name:"Cursor"}:void 0}const YE=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 ex(e){return YE.has(e.toLowerCase())}function tx(e){return`app/${e}`}function rx(e){return"object"==typeof e&&null!==e}function nx(e){return sx.includes(e)}function ox(e){if(!rx(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!rx(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!nx(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 sx=["pid","bundleId","path","appName"],ix=/^[+-]?\d+$/;var ax=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const cx="win32"===process.platform;function lx(e,t){return cx&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const ux=(0,s.join)((0,o.homedir)(),".cursor","projects"),dx=(0,s.join)((0,o.homedir)(),".cursor","worktrees");function hx(e){return lx(ux,e)&&e!==ux}function px(e){return lx(dx,e)&&e!==dx}function fx(e,t){const r=function(e){if(!lx(ux,e))return;if(e===ux)return;const t=(0,s.relative)(ux,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function mx(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function gx(e){const t=el(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:tl(e)}}}async function wx(e,t){const r=(0,bi.o1)(e,t);try{return mx(await(0,Ys.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==el(e))return mx(r,r,gx(e));try{if((await(0,Ys.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Ys.readlink)(r)}catch{}return mx(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return mx(await(0,Ys.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==el(e))return mx(r,r,gx(e))}return mx(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===el(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,Ys.realpath)(t);return mx((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==el(t))return mx(e,e,gx(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return mx(e,e,{status:"newFile"})}(r):mx(r,r,gx(e))}}}function yx(e){return"resolved"===e.status||"newFile"===e.status}function vx(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 bx({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o}){return"workspace"===r.boundary&&!Sx(t,n)&&!Sx(t,o)&&!(_x(t,r.allowPaths)||e!==t&&_x(e,r.allowPaths))}function Sx(e,t){return t.some((t=>(0,bi.BJ)(e,t)))}function kx(e){return e.flatMap((e=>{const t=(0,bi.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function _x(e,t){const r="win32"===process.platform?bi.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,bi.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&Yi(r(t),n)}))}const Cx=/(?{const t=await wx(e);return yx(t.resolution)?t.resolvedPath:(0,bi.o1)(e)})))}function Nx(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 jx(e){return[...new Set(e)]}function Lx(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Ux({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 Bx(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Wx(e){return"<"!==e.operator&&"<&"!==e.operator}function Hx(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function qx(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function zx({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(yx(a.resolution)){for(const e of r){const t=await o(e);if(yx(t.resolution)&&Ux({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:s}))return"workspace-file"}return n&&tP(a.resolvedPath,i)?"tmp-file":void 0}}function Gx(e){return jx(e.map((e=>e.trim())).filter(Boolean))}function Vx(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 Kx(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Jx(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new xr.r6({type:"word",value:e})));return new xr.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Zx(e,t={}){return{type:e,...t}}function Xx(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 Qx(e,t){if("workspace"===e&&void 0!==t)return t}const Yx={workspace:0,system:1};function eP(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 tP(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){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||!Ux({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 rP(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,ri.$b)(e.networkPolicy),n=(0,ri.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,ri._B)(e.networkPolicy),s=(0,ri._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!(Yx[i]>Yx[a])}class nP{constructor(e,t,r,n){this.command=e,this.requestedPolicy=t;const o=void 0!==r&&rP(t,r);this.state=o?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!rP(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function oP(e){return e?.type??"undefined"}const sP=["skills","skills-cursor","rules","plugins"];async function iP(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function aP(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function cP({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 lP=/^\s*Read\s*\((.*)\)\s*$/,uP=/^\s*Write\s*\((.*)\)\s*$/;class dP{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.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy}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]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]):[[],[]],i=r.map((e=>this.compileReadDenyMatcher(e))),a=e=>i.some((t=>t(e)));return async(e,r)=>a(e)||a(r)||n&&bx({requestedAbsolutePath:e,realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s})}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:Xx(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 Fx([...kx(e),...(0,ri.r5)()])}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,Zs.r_)(e)))),...sP.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,ri.W1)(e)??[]));return Fx([...this.rootDirectories,...r,...n])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,bi.o1)(e),o=await al(n);if(null===o)return{type:"unsafeResolution",message:Nx("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(!hx(o)&&!px(o)&&!t&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:o,requestedAbsolutePath:n});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const{perms:r,setting:n}=await this.readControlSetting();if("workspace"!==n.boundary||"unrestricted"===r.approvalMode)return!1;const o=await this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName);return!Sx(e,o)&&(!!bx({requestedAbsolutePath:t,realAbsolutePath:e,setting:n,resolvedWorkspaceRoots:o,resolvedAllowFolders:await this.resolvedReadAllowFolders(n.allowPaths)})&&{type:"needsApproval",approvalReason:n.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 shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Px(n,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const a=await wx(t);if(!yx(a.resolution))return{type:"unsafeResolution",message:vx(a.originalPath,a.resolution)};const c=a.resolvedPath,l=c;if(await this.ignoreService.isRepoBlocked(l))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",c))return{type:"permissionsConfig"};const u=a.originalPath.split(s.sep).pop()?.toLowerCase()??"",d=c.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===u||".cursorignore"===d)return{type:"permissionsConfig"};const h=hx(l),p=px(l),f=!h&&!p&&await this.ignoreService.isCursorIgnored(l);if(h||p);else if(f)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",c))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(c))return!1;const m=await this.getPermissions();if("workspace_readonly"===m.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===m.approvalMode)return!1;for(const e of this.rootDirectories){const t=await wx(e);if(!yx(t.resolution))continue;const r=t.resolvedPath;if((0,bi.BJ)(c,r)){const e=(0,s.relative)(r,c).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const g=async()=>{let e,t,n="";try{n=await sc(c),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,ax.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 w,y=!1;for(const e of this.rootDirectories){const t=await wx(e);if(!yx(t.resolution))continue;const r=t.resolvedPath;if((0,bi.BJ)(c,r)){y=!0,w=r;break}}const v=y?void 0:function(e){if(!px(e))return;const t=(0,s.relative)(dx,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(dx,t[0]):void 0}(c);if(!y&&void 0===v){if(function(e){return tP(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(c))return!1;if(fx(c,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(c.startsWith(e)){const e=c.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const b=w??v,S=c;let k=(0,s.relative)(b,S).split(s.sep);if(k=k.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&k.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${k[k.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,ri.OK)(c,b)){const e=k[k.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const _=await this.checkCursorFileProtection(k);if(_)return _;if(!0===m.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await g();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{Ix(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 al(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Nx("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}}:{kind:"allow"}}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(Rx.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:oP(l),requestedPolicyType:oP(n),effectiveRequestedPolicyType:oP(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Wr(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 Rx.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:oP(l),requestedPolicyType:oP(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.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,v="allowlist"===a&&i.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==v,S=v?v.map(Jx):d,k=void 0!==v?v.map(Vx):S.map((e=>[e.fullText.trim()].filter(Boolean))),_=void 0!==y?y.commands.map(Vx):k;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,ri.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,ri._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 C;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,ri.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,ri.wG)(Qx(e.readBoundary,e.additionalReadPaths),Qx(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),m&&Rx.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});const E=[],x=[];let P=[],I=[],R=[];const T=Gx(i.smartAllowlistDenylist??[]);if(T.length>0){I=[];const t=_.map((e=>e[0]??""));for(let e=0;e<_.length;e++){const r=_[e];if(r&&0!==r.length&&T.some((e=>Kx(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(Rx.info(e,"Command blocklist: commands require approval",{count:I.length}),E.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));Rx.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const n=k.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(WE(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),Gx(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=GE(P,R),t=e.length>0?e.join(", "):P.join(", ");x.push(`Not in allowlist: ${t}`)}C=o&&0===I.length,C&&Rx.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,$=S.map(((e,t)=>new nP(e,n,A,k[t])));if((0===S.length||f&&!b)&&!c){Rx.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:oP(n),userConfiguredPolicyType:oP(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const o={type:$w.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:w}};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{allRedirectsAreWorkspaceFileSafe: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 j=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:I});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return Rx.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=Wr(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&&Cx.test(r)||xx(r,Cx,Ex)||xx(r,/(?0&&(j.hasSecurityDenies||j.hasSoftDenies||!j.allCommandsRunnable);if(void 0!==g&&G.push(g),L&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),E.length>0&&(V||G.push(...E),z=!1),!V)if(b&&x.length>0)G.push(...x);else if(j.unapprovedCommands.length>0){const e=GE(this.generateAllowlistPatterns(j.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):j.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(j.hasSecurityDenies&&(V||(j.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),j.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${j.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=j.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");Rx.info(e,"Shell permissions: commands not in team allowlist",{commandCount:j.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J=G.join(" • "),Z=[];if(z){const e=void 0!==g?$.filter((e=>"allowlisted"!==e.state)):j.unapprovedCommands;Z.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const X=b&&x.length>0,Q=X?P:Z,Y=X&&R.length>0?R:void 0,ee="insecure_none"!==n.type&&"insecure_none"!==l.type,te="insecure_none"!==n.type,re=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,E.length>0?"command_blocklist":void 0,b&&x.length>0?"smart_allowlist_miss":void 0,j.unapprovedCommands.length>0?"unapproved_commands":void 0,j.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Rx.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:oP(n),userConfiguredPolicyType:oP(l),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:z,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:re,commandCount:$.length,unapprovedCommandCount:j.unapprovedCommands.length,deniedCommandCount:j.deniedCommands.length,notInTeamAllowlistCount:j.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSecurityDenies:j.hasSecurityDenies,hasSoftDenies:j.hasSoftDenies});const ne={type:$w.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:J,isSandboxAvailable:"allowlist"===a&&ee,isSandboxEnabled:"allowlist"===a&&te,canAllowlist:z,notAllowedCommands:Q,suggestedAllowlistEntries:Y,smartModeApprovalReason:g,smartModeApprovalRequestId:w}};r.onApprovalRequested?.();const oe=await this.pendingDecisionStore.requestApproval(ne);if(oe.approved){const e="unrestricted"===a?{type:"insecure_none"}:n;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:oe.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,d=l?c.commands.map(Jx):u;if(0===d.length)return!1;const h=l?c.commands.map(Vx):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Vx):h,f={type:"insecure_none"},m=d.map(((e,t)=>new nP(e,f,void 0,h[t])));if(await this.hasHardDeny(n,m))return!1;const g=Gx(o.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>Kx(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const w=await this.teamSettingsService.getAutoRunControls();if(void 0!==w&&m.some((e=>this.isInTeamBlocklist(w,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:w,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const{userSandboxDataFolderName:t,teamAdminPolicy:r}=await this.getPermissions(),n=void 0!==t&&t.length>0?(0,s.join)((0,o.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,i=await this.foldPerUserFilePolicy(e,n),a=i.skipStatsigDefaults?i:await this.applyStatsigDefaults(i),c=await this.loadPerRepoFilePolicy(a.type);if("unavailable"===r){const{policy:e}=await(0,ri.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,ri.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const l=void 0===r?await this.buildTeamAdminPolicy(a.type):Zx(a.type,function(e){return"workspace"===e.readBoundary?e:void 0===e.networkPolicy?{}:{networkPolicy:e.networkPolicy}}(r)),u=(0,ri._B)(e.networkPolicy),{policy:d}=await(0,ri.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:a,perRepo:c,teamAdmin:l});return u?{...d,networkPolicy:(0,ri.T6)()}:d}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,ri.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,ri.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,ri.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};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,ri.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,ri._B)(e.networkPolicy))return e;const r={default:"deny",allow:jx(t.allowlist)};return{...e,networkPolicy:(0,ri.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,ri.tv)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Zx(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await 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:jx(i.allowlist)}:{},...i.denylist.length>0?{deny:jx(i.denylist)}:{}}:void 0:(0,ri.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});return void 0===t?void 0:Zx(e,t)}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){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return 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=wx,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=Lx();for(const e of l){if(qx(e))continue;const o=u?Lx():d,{operator:s,targetText:l}=e,p=e.destinationFds;if(">&"===s){const e=Hx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===s){const e=Hx(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!Bx(s)||void 0===l){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await zx({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(Wx))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c,redirectsAllowlistSafe:l}}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?{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=this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:$w.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",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}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=oa({matchForms:t.parsingResult?ea({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(Rx.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.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==eP(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=eP(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){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return 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 n of e)WE(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?lP:uP}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=Qi(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,bi.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,bi.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 Yi(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{Px(o,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:a,providerIdentifier:c,args:l}=t,u=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:kC(r.annotationsJson)}(t,r?.annotations),d=e=>{this.mcpAllowlistLog?.(e)};if(d(`[permissions-service] shouldBlockMcp: toolName="${a}", providerIdentifier="${c}"`),await this.isComputerUseDisabledByAdminFor(c))return d(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${a}", providerIdentifier="${c}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,c,a))return d(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${a}", providerIdentifier="${c}"`),{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=cP({server:aP(c),tool:a});let b,S,k;switch(w.kind){case"block":return d(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${a}", providerIdentifier="${c}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${a}", providerIdentifier="${c}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${a}", providerIdentifier="${c}"`),!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?(d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0}):(d(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${a}", providerIdentifier="${c}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:c,toolName:a,annotations:u}):k&&await this.isMcpExplicitlyAllowed(e,c,a))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:a,...Ox(r,u),providerIdentifier:c,args:l,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(c),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:c,toolName:a,annotations:u});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,c,a);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${a}", providerIdentifier="${c}"`),!1;d(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${a}", providerIdentifier="${c}"`)}return d(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${a}", providerIdentifier="${c}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${a}`,approvalDetails:{type:"mcp",name:s,toolName:a,...Ox(r,u),providerIdentifier:c,args:l,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Ix(o)}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(aP(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=ox(e.meta?.["cursor/computerUseScope"])??ox(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])=>nx(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&&ix.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?QE(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&&ix.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:QE(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 JE(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":ZE.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.":XE.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=ex(o.app.bundleId)?void 0:cP({server:r.serverId,tool:tx(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=aP(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(aP(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||ex(e)?void 0:cP({server:this.computerUse.serverId,tool:tx(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??kC(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=aP(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}){Tx.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&&OE(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&&function(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=NE(e);return 0!==r.length&&t.some((e=>NE(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}(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 hP=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 pP=65536,fP=1048576,mP=(0,C.h)("LocalReadExecutor"),gP=async(e,t,r,n)=>{const o=setTimeout((()=>{mP.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function wP(e){return BigInt(Math.min(e,4294967295))}async function yP(e,t){if(0===t)return(0,Ys.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Ys.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function SP(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 kP=Buffer.from("\n---\n");function _P(e,t){const r=e.length;if(r<2*kP.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(kP,r-kP.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+kP.length,r-4).toString("utf-8"))?o:r}const CP=[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 EP(e){return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:e,reason:"File content is binary data, not text"})}})}function xP(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=PP(s,e),c=PP(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function PP(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 IP(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function RP(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 TP(e,t,r){const n=RP((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 AP(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=IP(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=fi(c,o)),{text:c,truncated:l}}function $P(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=IP(e.slice(t,o));const i=s.length>n||on&&(s=fi(s,n)),s.lengthn?{text:e.text+fi(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function DP(e,t){if(e.truncated)return e;const r=MP(e,t);return{text:r.text,truncated:r.truncated}}function OP(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=MP(n,"\n")),n=MP(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function FP(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 NP(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Yt:Math.min(Yt,e.maxChars+2)}function jP(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 LP extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function UP(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return BP(r)>t?t:0}return 0}function BP(e){return e>=240?4:e>=224?3:e>=192?2:1}class WP{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 LP}validate(e){let t=e;if(this.carry.length>0){const r=BP(this.carry[0]??0)-this.carry.length;if(e.length0?Math.min(t,fP):fP,o=await yP(e,r);return o.length===t&&(0,n.isUtf8)(o)||Ia(new ha.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===fP&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function zP(e){const t=await(0,Ys.stat)(e),r=await lc(e);if(r.isBinaryFile)return;const n=HP({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await qP(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function GP(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,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,j=0,L=!1,U=!1;const B=e=>{let t=e;return!L&&t.length>0&&(L=!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>=Yt,q=()=>v||w&&g>=Yt,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Yt-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:fi(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=Yt-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:fi(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++:j++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.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===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t1&&A>Yt;)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-UP(e));return Q=new WP(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 ha.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,ti.createReadStream)(t,{highWaterMark:pP,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 LP;throw e}return}const i=(0,ti.createReadStream)(t,{highWaterMark:pP,signal:e.signal,...s}).pipe(pa.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=DP(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&&vc(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)+pP,ae=e=>e.text.length>ie?{text:fi(e.text,ie),truncated:!0}:e,ce=()=>OP({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(OP({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class VP{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}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,i.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new tr.sV({result:{case:"error",value:new tr.F_({path:o,error:Si})}});const a=(0,bi.o1)(o,this.workspacePath),c=await gP(e,"permissionsService.shouldBlockFileRead",3e3,(()=>iP(this.permissionsService,a)));if(c){const r=await gP(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await hu(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:$w.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"}}(c,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new tr.sV({result:{case:"rejected",value:new tr.f4({path:a,reason:r.reason??""})}});if("denied"===r.kind)return new tr.sV({result:{case:"permissionDenied",value:new tr.lW({path:a})}})}void 0!==this.mcpStateAccessor&&_E(e,this.mcpStateAccessor,a);try{const r=await gP(e,"stat",3e3,(()=>(0,Ys.stat)(a)));if(r.isDirectory())return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=rr(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)}(a),i=function(e){const t=rr(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(a);if(o||i)return await this.readTerminalFile(e,a,r,t,i&&!o);const c=await gP(e,"getFormatForFile",3e3,(()=>lc(a))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(a),d=nc(a);if(l){const t=await gP(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await bC(e)}catch(t){const r=await SC(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await SC(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Ys.readFile)(a))));return"undecodable"===t.kind?new tr.sV({result:{case:"invalidFile",value:new tr.cW({path:a,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 tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t.image.data},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(u){const t=await gP(e,"readPdfBinary",3e3,(()=>(0,Ys.readFile)(a)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await gP(e,"readBinaryFile",3e3,(()=>(0,Ys.readFile)(a)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:wP(r.size),truncated:!1})}})}if(c.isBinaryFile)return EP(a);{const n=this.useStreamingRead,o=!n||await gP(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Yt){const n=await gP(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=HP(t,r.encodingHint);try{return await GP(e,t,r,o,n)}catch(o){if(o instanceof LP)return await GP(e,t,r,await qP(t.file,t.stats.size),n);throw o}}(e,{file:a,stats:r,format:c},t,o)));return new tr.sV({result:{case:"success",value:new tr.mE({path:a,output:{case:"content",value:jP(n.content,n.truncated,t)},totalLines:n.totalLines,fileSize:wP(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await gP(e,"readText",3e3,(()=>sc(a,t.encodingHint))),i=await gP(e,"countLines",3e3,(()=>ma(s))),l=function(e,t,r){const n=xP(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:TP(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,i,t);let u=l.content,d=!1;const h=NP(t);return u.length>h&&(u=jP(u.substring(0,h),!0,t),d=!0),u.lengthyP(t,r.size)));if(o&&(i=s,CP.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return EP(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=vP(e),o=_P(e,n);if("utf-8"!==SP(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=RP((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=$P(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=vP(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=RP((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=AP(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,NP(n));return new tr.sV({result:{case:"success",value:new tr.mE({path:t,output:{case:"content",value:jP(a.content,a.truncated,n)},totalLines:a.totalLines,fileSize:wP(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function KP(e){return Buffer.from(e,"utf16le").toString("utf16le")}var JP=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},ZP=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 XP(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 QP(e){return`Path '${e}' is neither a file nor a directory`}async function YP(e){const t=await(0,Ys.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function eI(e,t,r){const n=function(e,t){let r;for(const n of t)(0,bi.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 tI extends Error{}function rI(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function nI(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 oI(e){switch(e){case"content":return new oy.vD({result:{case:"content",value:new oy.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new oy.vD({result:{case:"files",value:new oy.T7({ripgrepTruncated:!0})}});case"count":return new oy.vD({result:{case:"count",value:new oy.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function sI(e,t){let r=Buffer.concat(e);t&&(r=r.subarray(0,r.lastIndexOf(10)+1));const n=r.toString("utf8");return n.includes("�")?{stdout:n,stdoutBytes:r}:{stdout:n}}function iI(e){return/^(utf-?16|ucs-?2)/i.test(e)}const aI=(0,C.h)("local-exec/grep"),cI=(0,E.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"]}),lI=(0,E.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"]});function uI(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function dI(e){try{return(0,ti.existsSync)(e)}catch{return"check_failed"}}function hI(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function pI(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 fI(e,t,r,n){return{...gI(e),...n,cwd:t,cwdExists:dI(t),errorMessage:tl(r),errorCode:el(r),errno:hI(r),syscall:pI(r,"syscall"),errorPath:pI(r,"path")}}function mI(e){return new Error(`Path does not exist: ${e}`)}function gI(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,ti.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,ti.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,ti.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,ti.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,ti.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,ti.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,ti.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 e=r.concat("node_modules.asar");try{t.asarExists=(0,ti.existsSync)(e)}catch{t.asarExists="check_failed"}const n=r.concat(o);try{if(t.asarUnpackedDirExists=(0,ti.existsSync)(n),t.asarUnpackedDirExists){const e=(0,s.join)(n,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,ti.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class wI{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;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}computeRelativeTarget(e,t){const r=(0,bi.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,bi.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,bi.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,bi.o1)(t.path,this.singleWorkspacePath??e);return(0,bi.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 Mc(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,Ys.stat)(e)).isFile())return;const{encoding:t}=await lc(e);return iI(t)?t.toLowerCase():void 0}catch{return}}((0,bi.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,bi.o1)(s.file,t),i=await al(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 xE(t,(e=>(0,bi.o1)(n(e),r)));return s.statTimedOut&&(aI.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),lI.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,wI.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),p=await this.buildArgs(t,r,"files_with_matches",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?wI.HARD_MAX_OUTPUT_LINES:wI.CLIENT_LIMIT_LINES,d=wI.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 sy;let s=0,i=0,a=0;for(;iy(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(l,u,d)),g=m.totalFiles>wI.CLIENT_LIMIT_LINES;let w=m.files;n&&(w=await this.keepNewestPage(h.ctx,w,t,(e=>e),a),g&&(w=w.join("\0").split("\0")));const y=(await this.filterBlockedFiles(w.map((e=>({file:e}))),t)).map((({file:e})=>e)),v=w.length-y.length,b=new oy.T7({files:y,totalFiles:uy(m.totalFiles-v),clientTruncated:g,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new oy.vD({result:{case:"files",value:b}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}var l,u,d}async runCountMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),p=await this.buildArgs(t,r,"count",n),f=await this.executeRg(h.ctx,t,p,void 0,o,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=n?wI.HARD_MAX_OUTPUT_LINES:wI.CLIENT_LIMIT_LINES,d=wI.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 sy;let i=0;for(;iy(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}}(l,u,d)),g=n?await this.keepNewestPage(h.ctx,m.counts,t,(e=>e.file),a):m.counts,w=await this.filterBlockedFiles(g,t),y=w.reduce(((e,t)=>e+t.count),0),v=g.length-w.length,b=g.reduce(((e,t)=>e+t.count),0)-y,S=new oy.xA({counts:w.map((e=>new oy.sS({file:e.file,count:uy(e.count)}))),totalFiles:uy(m.totalFiles-v),totalMatches:uy(m.totalMatches-b),clientTruncated:m.totalFiles>wI.CLIENT_LIMIT_LINES,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new oy.vD({result:{case:"count",value:S}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}var l,u,d}async runContentMode(e,t,r,n,o,s,a){const c={stack:[],error:void 0,hasError:!1};try{const l=JP(c,(0,i.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),u=await this.buildArgs(t,r,"content",n),d=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,h=wI.CLIENT_LIMIT_LINES*(d?2:1),p=await this.executeRg(l.ctx,t,u,h,o,s,a);this.throwOnRipgrepFailure(p,t,r);const f=await this.decodeLinesAsRead(l.ctx,p,t,a),{byFile:m,totalLines:g,totalMatchedLines:w,clientTruncated:y,ripgrepTruncated:v}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return JP(o,(0,i.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 sy;let a=0,c=0,l=0,u=0;for(;iy(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:uy(l),totalMatchedLines:uy(a),totalFiles:uy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{ZP(o)}}(f,wI.CLIENT_LIMIT_LINES,h,l.ctx),b=Array.from(m.values()),S=await this.filterBlockedFiles(b,t),k=b.filter((e=>!S.includes(e))),_=k.reduce(((e,t)=>e+t.matches.length),0),C=k.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),E=n?await this.orderNewestFirst(l.ctx,S,t,(e=>e.file),a):S,x=new oy.Zp({matches:E.map((e=>new oy.uI({file:e.file,matches:e.matches.map((e=>new oy.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:uy(g-_),totalMatchedLines:uy(w-C),clientTruncated:y,ripgrepTruncated:v||p.timedOut||p.stdoutByteCapped});return{result:new oy.vD({result:{case:"content",value:x}}),timedOut:p.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{ZP(c)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const a=t.stdoutBytes;if(void 0===a)return t.stdout;const c=JP(s,(0,i.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),l=function(e,t){const r=[],o=new sy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&iy(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)))],d=new Map,h=performance.now()+wI.LINE_ENCODING_TIMEOUT_MS;let p=0;for(;p{let d=!1,h=!1;const p=()=>{h||(h=!0,c.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(wI.ripgrepTimeoutError());let f;try{const e=s;f=(0,ri.spawnInSandbox)((0,ri.Ko)(),r,{cwd:t},e),0}catch(r){if(p(),uI(r)){const n=(0,ri.Ko)();if(aI.error(e,"rg_diagnostics.spawn_throw",void 0,fI(n,t,r,a)),!1===dI(t))return u(mI(t))}return u(r)}const m=[],g=[];let w=0,y=0,v=0,b=!1,S=!1;const k=()=>{if(!d)try{p();const e=sI(m,!0);""===e.stdout?u(wI.ripgrepTimeoutError()):i({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:S}),f.kill()}catch{}};o.addEventListener("abort",k,{once:!0});const _=()=>{o.removeEventListener("abort",k),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",_,{once:!0}),f.stdout?.on("data",(e=>{if(!S&&!b)if(w+=e.length,w>l){S=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,b=!0;try{f.kill()}catch{}break}v+=r;const o=t>=0?e.subarray(0,t):e;m.push(o)}else m.push(e)})),f.stderr?.on("data",(e=>{y+=e.length,y<=l&&g.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_),p(),uI(r)){const n=(0,ri.Ko)();if(aI.error(e,"rg_diagnostics.spawn_enoent",void 0,fI(n,t,r,a)),!1===dI(t))return void u(mI(t))}u(r)})),f.on("close",(t=>{d=!0,o.removeEventListener("abort",k),e.signal.removeEventListener("abort",_);const r=sI(m,S),n=Buffer.concat(g).toString("utf8");p(),i({...r,stderr:n,exitCode:t??0,timedOut:!1,stdoutByteCapped:S})}))}))}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 al(t[0]);return null===r?{error:XP(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await YP(t[0])?{error:QP(e)}:{resolvedTarget:r}}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const a=JP(n,(0,i.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(o=l)&&"files_with_matches"!==o&&"count"!==o)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c},h=Gi(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,bi.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new oy.Ud({result:{case:"error",value:new oy.ts({error:bi.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 oy.Ud({result:{case:"error",value:new oy.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&_E(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,bi.BJ)(s,o))continue;const i=await al(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await YP(s))return new oy.Ud({result:{case:"error",value:new oy.ts({error:QP(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&_E(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:XP(m.path);return new oy.Ud({result:{case:"error",value:new oy.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?rI(wI.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=oI(u),n++,o=!0;continue}if(!1===dI(s))return new oy.Ud({result:{case:"error",value:new oy.ts({error:`Path does not exist: ${s}`})}});const i=t??rI(wI.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 tI))throw t;if(r[s]=oI(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(nI));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw wI.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=>eI(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 oy.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 oy.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 oy.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new oy._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,bi.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new oy.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,bi.o1)(m.path,this.singleWorkspacePath);try{await(0,Ys.stat)(e)}catch(t){return new oy.Ud({result:{case:"error",value:new oy.ts({error:`Path does not exist: ${e}`})}})}}return new oy.Ud({result:{case:"error",value:new oy.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){n.error=e,n.hasError=!0}finally{ZP(n)}var o}}wI.MAIN_TIMEOUT_MS=25e3,wI.INDEXED_GREP_TIMEOUT_MS=25e3,wI.INDEXED_GREP_CONTEXT_TIMEOUT_MS=wI.INDEXED_GREP_TIMEOUT_MS+100,wI.HARD_MAX_OUTPUT_LINES=1e4,wI.CLIENT_LIMIT_LINES=2e3,wI.LINE_ENCODING_TIMEOUT_MS=2e3,Nn.object({record_v:Nn.number().int().nullish(),pid:Nn.number().int().nonnegative().nullish(),version:Nn.string().nullish(),started_at:Nn.number().nullish(),control_sock:Nn.string().nullish(),runtime_dir:Nn.string().nullish(),data_dir:Nn.string().nullish(),config_path:Nn.string().nullish(),log_path:Nn.string().nullish(),metrics_addr:Nn.string().nullish(),exe:Nn.string().nullish()}),Nn.object({mountpoint:Nn.string().nullish(),capabilities:Nn.array(Nn.string()).nullish(),nfs_transport:Nn.string().nullish(),bind_ignored:Nn.object({active:Nn.array(Nn.string()).nullish()}).passthrough().nullish()}),Nn.object({daemon_alive:Nn.boolean().nullish(),mounts:Nn.array(Nn.unknown()).nullish(),data_plane:Nn.object({enabled:Nn.boolean().nullish()}).passthrough().nullish()});const yI=Nn.number().int().nonnegative(),vI=Nn.object({line_no:Nn.number().int().positive(),kind:Nn.enum(["match","before","after"]),text:Nn.string().optional(),bytes:Nn.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Nn.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Nn.object({type:Nn.literal("file"),path:Nn.string(),lines:Nn.array(vI)}),Nn.object({type:Nn.literal("summary"),files_searched:yI,more:Nn.boolean(),stop_reason:Nn.string().nullable(),skipped:Nn.object({over_size:yI,size_unknown:yI,budget_exhausted:yI,fetch_failed:yI,unreadable:yI})}),Nn.object({type:Nn.string()}),(0,C.h)("local-exec/grove-grep");var bI=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),SI=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},kI=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 _I{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{SI(r,(0,i.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,bi.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Ys.stat)(n)}catch(e){return"ENOENT"===el(e)?function(e){const t=rr(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:"No active terminals."})}}):new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:`Path does not exist: ${n}`})}}):new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:tl(e)})}})}if(!r.isDirectory())return new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Gi(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 bI.fv({result:{case:"timeout",value:new bI.ze({directoryTreeRoot:a})}}):new bI.fv({result:{case:"success",value:new bI.PC({directoryTreeRoot:a})}})}catch(e){return new bI.fv({result:{case:"error",value:new bI.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{kI(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return SI(o,(0,i.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{kI(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const a={stack:[],error:void 0,hasError:!1};try{SI(a,(0,i.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const c=(0,s.resolve)(t),l=new bI.vq({absPath:c,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(c,l);const d={charactersUsed:c.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=Fc(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:n,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,s.resolve)(t,e),n=await al(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,c,u,d,o)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){a.error=e,a.hasError=!0}finally{kI(a)}}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 bI.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]=uy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=uy(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 bI.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)}}var CI=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 EI=1e4,xI=5e3,PI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class II{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,tEI&&(this.fullOutput="")}getOutput(){return this.totalChars<=EI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=EI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class RI{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=_i-this.kept.length;this.full=e.length>=t,this.kept+=fi(e,t)}get text(){return this.kept}}function TI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class AI{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 xr.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new xr.QR(o)};return new xr.W4({result:i,sandboxPolicy:Vi(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,ri.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new II,a=new RI,l=new RI;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,ri.ue)((0,ri.Xw)({...process.env,...PI,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,Sl.D9)(bl.spawn,y.executable,y.args,w):(0,ri.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:dy(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=xr.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=xr.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:TI(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,i.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,i.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,bi.o1)(t.workingDirectory||this.defaultCwd),a=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let c=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId},c);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new xr.W4({result:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new xr.W4({result:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:s,reason:pu(l.reason)})}});c=l.policy,Di()&&(c=Ui(o,t.parsingResult)),c&&"insecure_none"!==c.type&&(c={...c,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:c,timeoutMs:a});return this.buildResult({args:t,workingDirectory:s,processResult:u,sandboxPolicy:c})}catch(e){r.error=e,r.hasError=!0}finally{CI(r)}}}var $I=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MI(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DI{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:MI(t.cursor),advance:!1!==t.advance});return new $I.Ev({result:{case:"success",value:new $I.iS({events:e.events.map((e=>new $I.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 $I.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $I.Ev({result:{case:"error",value:new $I.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OI{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Cr.nt({result:{case:"error",value:new Cr.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Cr.nt({result:{case:"success",value:new Cr.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class FI{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,P.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 NI(e,t){return`${e}:${(0,Js.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function jI(e,t){const r=new ei.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=NI(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 LI=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),UI=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class BI{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"),WI(HI(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),WI(new LI.GL({result:{case:"success",value:new LI.uX({path:t.path,diagnostics:e.map(qI)})}}),await o))}catch(e){return r("unavailable"),WI(HI(t.path,e instanceof Error?e.message:String(e)),await o)}}}function WI(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function HI(e,t){return new LI.GL({result:{case:"error",value:new LI.HW({path:e,error:t})}})}function qI(e){return new UI.oQ({severity:zI(e.severity),range:new yl.Q6({start:new yl.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new yl.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function zI(e){switch(e){case 1:return UI.h_.ERROR;case 2:return UI.h_.WARNING;case 3:return UI.h_.INFORMATION;case 4:return UI.h_.HINT;default:return UI.h_.UNSPECIFIED}}class GI{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 UI.Ek({result:{case:"success",value:new UI.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new UI.Ek({result:{case:"error",value:new UI.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new UI.Ek({result:{case:"error",value:new UI.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{VI(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 UI.oQ({severity:this.convertSeverity(e.severity),range:e.range?new yl.Q6({start:new yl.yX({line:e.range.start.line,column:e.range.start.character}),end:new yl.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 UI.h_.ERROR;case 2:return UI.h_.WARNING;case 3:return UI.h_.INFORMATION;case 4:return UI.h_.HINT;default:return UI.h_.UNSPECIFIED}}}async function JI(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 Qw().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 ZI(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 ZI(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 ZI{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 XI=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]=eR(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=rR(e)}],[/^\+\+\+\s/,e=>{u(),n.to=rR(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},QI=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,YI=/^(a|b|i|w|c|o|1|2)\//,eR=e=>{const t=e?.match(QI);return t?.map((e=>e.replace(YI,"").replace(/("|')$/,"")))},tR=/^\\?['"]|\\?['"]$/g,rR=e=>{let t=nR(e,"-+").trim();return t=sR(t),t.replace(tR,"").replace(YI,"")},nR=(e,t)=>{if(e=aR(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=iR(t);return e.replace(new RegExp(`^${r}+`),"")},oR=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,sR=e=>{const t=oR.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},iR=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${aR(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,aR=e=>`${e??""}`,cR=(0,C.h)("local-mercurial-diff"),lR=5242880,uR="0000000000000000000000000000000000000000";let dR,hR;async function pR(e,t,r={}){const n=await async function(){if(void 0===dR&&(dR=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 Ys.stat(t)).isFile())continue;return"win32"!==process.platform&&await Ys.access(t,ti.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===dR){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return dR}();return await new Promise(((o,s)=>{const i=(0,bl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new xc.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"}`))}}))}))}async function fR(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Ys.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!==hR)return hR;const e=await Ys.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await pR(e,["help","environment"]);hR=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){hR=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Ys.rm(e,{recursive:!0,force:!0})}return hR}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await pR(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Ys.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function mR(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 gR(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 wR(e){const t=s.default.resolve(e);try{return await Ys.realpath(t)}catch{return t}}function yR(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 vR(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function bR({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await pR(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>lR?"":pR(e,["cat","-r",t,"--",r])}async function SR(e,t,r){const n=function(e){switch(e){case Fn.ek.NAME_STATUS:return Fn.ek.NAME_STATUS;case Fn.ek.NAME_STATUS_AND_NUMSTAT:return Fn.ek.NAME_STATUS_AND_NUMSTAT;case Fn.ek.FILE_DIFFS:return Fn.ek.FILE_DIFFS;case Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Fn.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await pR(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){vR(t),r.push("log");const n=(await pR(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===uR)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await pR(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==uR)return n;const o=(await pR(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==uR)return o;const s=(await pR(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:uR}({cwd:t,baseRef:r.baseRef,commands:o});else if(vR(r.baseRef),o.push("log"),a=(await pR(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(vR(r.ref),o.push("log"),c=(await pR(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 pR(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Fn.o$({diffs:XI(t).map((e=>function(e){const t=new Fn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Fn.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:Fn.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 pR(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 Ys.stat(r);if(n.size>lR){const t=await async function(e){const t=(0,Js.createHash)("sha256"),r=await Ys.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 Ys.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 Fn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=yR(e.contents);if(0===t.length)return new Fn.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Fn.QP({from:"/dev/null",to:e.path,chunks:[new Fn.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!==Fn.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Fn.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 bR({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 Ys.stat(e);t.afterFileContents=r.size>lR?"":await Ys.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await bR({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=yR(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,Js.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 pR(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:uR,g=(await pR(t,["status","-0"])).length>0}cR.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Fn.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 cR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return cR.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const kR=(0,C.h)("local-git-diff");function _R({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function CR(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 _R(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function ER(e){const t=XI(e);return new Fn.o$({diffs:t.map((e=>function(e){const t=new Fn.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Fn.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:Fn.Wf.UNSPECIFIED})}function xR(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:ma(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 PR=["main","master","develop"];async function IR(e,t){const r=s.default.join(e,t),n=await Ys.lstat(r);if(n.isSymbolicLink())return{contents:await Ys.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Ys.readFile(r,"utf8"),path:t,isSymlink:!1}}async function RR(e,t,r){const n=Qw(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await CR(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 wR(t);let n=await wR(e);if(mR(n,r))return;let o=!1;for(;gR(n,r)&&!mR(n,r);){try{if((await Ys.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?fR(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await fR(e)?"none":"mercurial"}(t,o);if(kR.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw kR.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return SR(e,t,r);const a=function(e){switch(e){case Fn.ek.NAME_STATUS:return Fn.ek.NAME_STATUS;case Fn.ek.NAME_STATUS_AND_NUMSTAT:return Fn.ek.NAME_STATUS_AND_NUMSTAT;case Fn.ek.FILE_DIFFS:return Fn.ek.FILE_DIFFS;case Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Fn.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Fn.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await CR(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of PR){const r=`origin/${t}`;try{return await CR(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await CR(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await CR(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 CR(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=ER(h);else{const t=_R(d);if(r.computePatchId||!await async function(e){return(await CR(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 CR(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),kR.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 CR(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 IR(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${xR([e])}\n\\ No newline at end of file`:await CR(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...ER(t).diffs)}}if(a!==Fn.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Fn.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 CR(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 CR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await IR(t,s.to)).contents}catch{try{s.afterFileContents=await CR(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){kR.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 JI({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 CR(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){kR.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,xR(f))):void 0,v=!0===r.returnHeadSha?(await CR(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await CR(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Fn.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 TR{async execute(e,t){return RR(e,t.cwd,t)}}var AR=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class $R{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 AR.M({allowlisted:r})}}var MR=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),DR=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 OR(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function FR(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function NR(e){return e instanceof Error?e.message:String(e)}function jR(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: ${NR(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const LR=(0,ha.promisify)(bl.execFile);class UR{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(!OR(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),UR.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 Ys.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 Ys.mkdir(this.stagingDir,{recursive:!0}),await Ys.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:MR.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:MR.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:MR.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 Ys.rename(e,t)}catch(e){if(!FR(e,"EXDEV"))throw e}try{await Ys.copyFile(e,t)}catch(e){throw await Ys.rm(t,{force:!0}).catch((()=>{})),e}try{await Ys.unlink(e)}catch(e){throw await Ys.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 Ys.open(e,"wx");return await t.close(),e}catch(e){if(!FR(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,Sl.D9)(LR,"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,Sl.D9)(LR,"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:UR.PROXY_TARGET_FPS,includeBrandTag:!0}),await Ys.access(n,Ys.constants.R_OK)}catch(t){const r=(0,i.fU)(e);throw r?.setAttribute("error.type",function(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}(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,Sl.D9)(LR,"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 ${UR.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${UR.PROXY_TARGET_FPS}fps`)}return UR.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Ys.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await Fg(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${UR.DEFAULT_REFRESH_RATE}Hz`),o=UR.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${UR.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${UR.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",UR.PROXY_PRESET,"-crf",String(UR.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,Sl.D9)(bl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.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);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.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);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.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:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,Sl.D9)(bl.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 Ys.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(OR(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{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),FR(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();try{const o=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!OR(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${NR(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await Ys.access(d,Ys.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=FR(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${NR(e)}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:jR(t,r,a,n)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=NR(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:jR(o,r,a,n)})}})}const m={profileVersion:UR.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:UR.PROXY_TARGET_FPS,codec:"h264",profile:UR.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:o,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await Ys.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await Ys.rm(g,{force:!0}).catch((()=>{})),e}try{await Ys.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${NR(e)}`)}return this.clearActiveRecordingIfCurrent(r),new MR.Tj({result:{case:"saveSuccess",value:new MR.ol({path:g,recordingDurationMs:sr.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new MR.Tj({result:{case:"failure",value:new MR.yH({error:NR(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,i.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`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===MR.$u.UNSPECIFIED)return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case MR.$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 Ys.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Ys.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await Fg(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,o);r=a;const l=function(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}(this.display);n=new zg({displayNum:l,resolution:i}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new MR.Tj({result:{case:"startSuccess",value:new MR.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await Ys.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new MR.Tj({result:{case:"failure",value:new MR.yH({error:e instanceof Error?e.message:String(e)})}})}}case MR.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new MR.Tj({result:{case:"failure",value:new MR.yH({error:"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 MR.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new MR.Tj({result:{case:"failure",value:new MR.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!OR(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await Ys.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new MR.Tj({result:{case:"discardSuccess",value:new MR.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await Ys.rm(r,{force:!0,recursive:!0}),n=!0}catch{}this.activeRecording=null;const o=t instanceof Error?t.message:String(t),s=n?"":`. Session may remain at: ${r}`;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new MR.Tj({result:{case:"failure",value:new MR.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{DR(r)}}}async function BR(e){const t=await(0,Ys.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 BR(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 WR(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(...WR(t,e,s))}))}return n}async function HR(e){if(!await(0,Ys.access)(e,Ys.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await BR(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>WR(e,"",r===t.length-1))).join("\n")}async function qR(e,t){return HR(s.join(e,"agent-notes",t))}async function zR(e){return HR(s.join(e,"agent-notes","shared"))}UR.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,UR.PROXY_TARGET_WIDTH=1920,UR.PROXY_TARGET_FPS=60,UR.PROXY_CRF=17,UR.PROXY_PRESET="veryfast",UR.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",UR.DEFAULT_REFRESH_RATE=60;var GR=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},VR=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 KR=(0,C.h)("local-exec:request-context"),JR=Symbol("sectionLoadTimedOut");async function ZR(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{GR(o,(0,i.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{VR(o)}}async function XR(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 QR(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,ri.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,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Nr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:sr.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 YR={type:"object",properties:{},additionalProperties:!1};function eT(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Ut.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new ds.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?sr.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tT(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 ds.E$({toolName:e.toolName,..._C(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?sr.Value.fromJson(e.inputSchema):void 0}}})));return!Lt(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===UC))||o.push(new ds.E$({toolName:UC,...r?{}:{description:BC,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(YR)}:{inputSchema:sr.Value.fromJson(YR)}}})),new ds.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 ds.U_({enabled:!0,mcpDescriptors:n})}function rT(e){const t=e?.trim();return t||void 0}function nT(e,t){const r=function(e){return rT(e.serverIdentifier)}(e);if(r)return r;const n=rT(e.serverName);return n?t.get(n)??n:void 0}class oT{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(KR.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(KR.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=>nT(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=>nT(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=>(KR.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:zt(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sT(e){return new er._W({result:{case:"success",value:new er.pv({servers:e.servers.map((e=>new er.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new ds.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?sr.Value.fromJson(e.inputSchema):void 0,metaJson:Bt(e._meta),..._C(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iT{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==er.ew.FORCE_IF_MISSING&&t.refreshPolicy!==er.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 sT({...r,servers:n})}return sT(r)}}class aT{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.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:I,isAttributionDisabledByAdmin:R,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=I,this.isAttributionDisabledByAdmin=R,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.onRequestContext=c.onRequestContext,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),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)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,ye.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=GR(r,(0,i.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Vc(n.ctx,this.gitExecutor,t),s=o?await Kc(n.ctx,this.gitExecutor,o):void 0,a={repoPath:o??void 0,remoteUrl:void 0!==s?Jc(s):void 0};this.cachedWorkspaces.set(t,a)}catch(e){r.error=e,r.hasError=!0}finally{VR(r)}}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,ye.q6)(),r=GR(e,(0,i.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)&&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{VR(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GR(t,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},a=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[c,l,u,d]=await Promise.all([a("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),a("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),a("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),a("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-o);return h>1e3&&KR.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...s,ruleCount:c.length}),{rules:[...this.additionalRules,...c],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{VR(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=GR(r,(0,i.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,a=!0;const c=(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 i=o?.[e];if(void 0!==i)return void 0!==r.repoPath&&void 0===i.gitStatus&&(a=!1),new Nr.DS({path:r.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:zc(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:c,branchName:l}=await async function(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(ZR(e,t,r,n)),o(XR(e,t,r,n))]);return{status:s,branchName:i}}(n.ctx,t.gitExecutor,r.repoPath,3e3);return void 0===c&&(a=!1),new Nr.DS({path:r.repoPath,status:c,branchName:l,remoteUrl:r.remoteUrl,isOriginBacked:zc(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:c,gitRepoInfoComplete:s,gitStatusInfoComplete:s&&a}}catch(e){r.error=e,r.hasError=!0}finally{VR(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=GR(n,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,a=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=GR(e,(0,i.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath){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{VR(e)}},c=performance.now(),l={},u=(e,t)=>{const r=performance.now();return t.finally((()=>{l[e]=Math.round(performance.now()-r)}))},d=e=>function(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(JR)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}(e,this.sectionLoadTimeoutMs),h=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),[p,f,m,{gitRepos:g,gitRepoInfoComplete:w,gitStatusInfoComplete:y},v,b,S,k,_,C]=await Promise.all([u("globalCache",d(a())),u("mcpState",d(h((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(o.ctx))))),u("env",QR(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})),u("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),u("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?qR(s,t.notesSessionId):Promise.resolve(void 0)),u("sharedNotes",this.agentNotesEnabled&&s?zR(s):Promise.resolve(void 0)),u("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),u("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),u("agentSkills",d(h((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([]))))),u("adminCommandDenylist",d(h((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))]),E=p===JR,x=f===JR,P=_===JR,I=C===JR,R=E?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:p,T=x?{servers:[]}:f,A=P?[]:_,$=I?void 0:C;(E||x||P||I)&&KR.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:E,mcpState:x,agentSkills:P,adminCommandDenylist:I});const M=performance.now()-c;for(const[e,t]of Object.entries(l))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(M)),M>1e3&&KR.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(M),...l});const D=this.mcpMetaToolEnabled?tT(T,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,O=this.attributionConfigProvider?.get(),F=!k&&(O?.attribution?.attributeCommitsToAgent??!0),N=!k&&(O?.attribution?.attributePRsToAgent??!0),j=new Nr.bb({rules:R.rules,env:m,gitRepos:g,gitRepoInfoComplete:w,repositoryInfo:R.codebaseReference?[{relativeWorkspacePath:R.codebaseReference.relativeWorkspacePath,repoName:R.codebaseReference.repoName,repoOwner:R.codebaseReference.repoOwner,isTracked:R.codebaseReference.isTracked,isLocal:R.codebaseReference.isLocal,orthogonalTransformSeed:R.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:R.codebaseReference.pathEncryptionKey}]:[],...eT(T,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:v,sharedNotesListing:b,customSubagents:R.customSubagents,mcpFileSystemOptions:S,mcpMetaToolOptions:D,supportsMcpAuth:!0,commitAttributionMessage:F?"enabled":void 0,prAttributionMessage:N?"enabled":void 0,agentSkills:A,adminCommandDenylist:$?.rules??[]});return null!==R.cloudRule&&void 0!==R.cloudRule&&(j.cloudRule=R.cloudRule),this.reportSectionCompleteness&&(j.rulesInfoComplete=!E,j.customSubagentsInfoComplete=!E,j.agentSkillsInfoComplete=!P,j.mcpInfoComplete=!x,j.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==S,j.envInfoComplete=!0,j.gitStatusInfoComplete=y),j}catch(e){n.error=e,n.hasError=!0}finally{VR(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=GR(r,(0,i.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 Nr._G({result:{case:"success",value:new Nr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(tl(e)),new Nr._G({result:{case:"error",value:new Nr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{VR(r)}}}function cT(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===xr._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lT=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 uT{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new xr.W4({result:{case:"success",value:new xr.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Vi(e.sandboxPolicy)}):new xr.W4({result:{case:"failure",value:new xr.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:Vi(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?{perRepo: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?xr.Lv.TIMEOUT:xr.Lv.USER_ABORT:xr.Lv.UNSPECIFIED:void 0,u=dy(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 xr.W4({result:{case:"timeout",value:new xr.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:Vi(o)}):e.signal.aborted?new xr.W4({result:{case:"rejected",value:new xr.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:Vi(o)}):new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:Vi(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,i.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,i.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0,a=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),c=cT(t),l=(0,bi.o1)(a);if(!t.parsingResult)return new xr.W4({result:{case:"spawnError",value:new xr.mJ({command:o,workingDirectory:l,error:"Parsing result is required"})}});let u;if(Hr(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId},s);if("block"===e.kind)return new xr.W4({result:fu(o,l,e.reason)});u=s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:l,timeout:c,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t)},s);if("block"===e.kind)return new xr.W4({result:fu(o,l,e.reason)});u=e.policy}if(Di()&&(u=Ui(o,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await cl(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(n,t,a,c,u)}catch(e){r.error=e,r.hasError=!0}finally{lT(r)}}}var dT=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hT{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new xr.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dT.e({allowlisted:n})}}class pT{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new xr.jK({status:xr.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fT=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 mT=(0,C.h)("local-exec:shell-stream");class gT{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===xr.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:xr.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:xr.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 wT(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yT{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}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,ye.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new xr.jK({status:xr.iA.ACCEPTED,shellResult:o}):new xr.jK({status:xr.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(Rr).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:wT()},""!==e.toolCallId&&e.timeoutBehavior===xr._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,i.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?Gi(t.requestedSandboxPolicy):void 0;const a=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),c=cT(t),l=(0,bi.o1)(a),u=Date.now(),d=new xr.HO(li(o).structured),h=ia({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new xr.FI({event:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:pu(p.reason)})}}));if(mT.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}),Hr(t))mT.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined"});else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:l,timeout:c,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Br(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wT()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mT.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 xr.FI({event:{case:"permissionDenied",value:new xr.jn({command:o,workingDirectory:l,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=pu(n.reason);return void(yield new xr.FI({event:{case:"rejected",value:new xr.pZ({command:o,workingDirectory:l,reason:r})}}))}s=n.policy,mT.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}if(Di()&&(s=Ui(o,d)),s&&"insecure_none"!==s.type){const e=await cl(this.ignoreService);s={...s,ignoreMapping:e}}yield new xr.FI({event:{case:"start",value:new xr.tD({sandboxPolicy:Vi(s)})}});const f=t.timeoutBehavior===xr._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?{perRepo:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:a,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()),c));const k=f?new gT(b[Symbol.asyncIterator](),c):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new xr.W4({result:{case:"success",value:new xr.QR({shellId:E,pid:C,command:o,workingDirectory:l,msToWait:dy(Date.now()-u),backgroundReason:xr.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&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 D=k?.iterate()??b;try{for await(const r of D)if("stdout"===r.type)x+=r.data,yield new xr.FI({event:{case:"stdout",value:new xr.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new xr.FI({event:{case:"stderr",value:new xr.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;I=!0,r.aborted&&(n=e.signal?.aborted?xr.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?xr.Lv.TIMEOUT:xr.Lv.USER_ABORT),yield new xr.FI({event:{case:"exit",value:new xr.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:dy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof ri.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mT.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new xr.FI({event:{case:"sandboxUnsupported",value:new xr.rI({command:o,workingDirectory:l,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||I||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===xr.Jg.USER_REQUEST?xr.Jg.USER_REQUEST:xr.Jg.TIMEOUT,s=n===xr.Jg.USER_REQUEST?Date.now()-u:c;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:l,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new xr.FI({event:{case:"backgrounded",value:new xr.Y9({shellId:r,command:o,workingDirectory:l,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new xr.FI({event:{case:"exit",value:new xr.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:xr.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{fT(n)}}}const vT={kind:"absent"};class bT{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 ei.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(xT(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=xT(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=xT(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=xT(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=xT(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=xT(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}async function ST(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await ET(t);const r=await _T(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}class kT{constructor(e,t,r,n){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n}async execute(e,t,r){const n=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,bi.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===n)return this.inner.execute(e,t,r);const o=this.reads.begin(n);try{let s,i;try{s=await iP(this.permissionsService,n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}if(!1!==s&&"needsApproval"!==s.type)return await this.readAndForget(e,t,r,n,o);if(!1!==s){const s=await this.inner.execute(e,t,r),i=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await _T(t)}catch{return}}(s,n.resolvedPath);return this.commit(n,o,s,i),s}try{i=await _T(n.resolvedPath)}catch{return await this.readAndForget(e,t,r,n,o)}const a=await this.inner.execute(e,t,r);return this.commit(n,o,a,i),a}finally{this.reads.end(n,o)}}commit(e,t,r,n){"fileNotFound"!==r.result.case?void 0===n||"success"!==r.result.case||"content"!==r.result.value.output.case?this.reads.forget(e,t):this.reads.record(e,{kind:"fingerprint",...n},t):this.reads.record(e,vT,t)}async readAndForget(e,t,r,n,o){const s=await this.inner.execute(e,t,r);return this.reads.forget(n,o),s}}async function _T(e){try{const t=await(0,Ys.stat)(e);if(!t.isFile()||t.size>Yt)return}catch(e){return PT(e)}let t;try{t=await(0,Ys.open)(e,function(){const e=ti.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Yt)return;const n=(0,Js.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Yt;){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>Yt)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return PT(e)}finally{await(t?.close())}}function CT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}async function ET(e){try{return await(0,Ys.stat)(e),!0}catch(e){if(IT(e))return!1;throw e}}function xT({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function PT(e){if(!IT(e))throw e}function IT(e){const t=el(e);return"ENOENT"===t||"ENOTDIR"===t}var RT=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class TT{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new RT.M({allowlisted:r})}}var AT=r("node:constants");class $T extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}const MT=new ha.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),DT=new Map([["€",128],["‚",130],["ƒ",131],["„",132],["…",133],["†",134],["‡",135],["ˆ",136],["‰",137],["Š",138],["‹",139],["Œ",140],["Ž",142],["‘",145],["’",146],["“",147],["”",148],["•",149],["–",150],["—",151],["˜",152],["™",153],["š",154],["›",155],["œ",156],["ž",158],["Ÿ",159]]),OT=new Set([194,195,226,239]),FT=/\p{Lu}/u,NT=new Set([" ","­","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),jT=new Set(["¿","¡"]),LT=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,jT],[209,jT],[211,jT],[218,jT],[220,jT]]),UT=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),BT=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function WT(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:DT.get(e)}function HT(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&&FT.test(e[t-1]))return}else{if(NT.has(s))return;if(!0===LT.get(r)?.has(s))return;if(3===n&&UT.has(s)&&NT.has(e[t+2]))return}let i;try{i=MT.decode(o)}catch{return}return BT.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function qT(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=HT(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const zT=["mojibake","replacement_chars"];function GT(e){return e<=1?"1":e<6?"2-5":"6+"}function VT(e){return e<=0?"0":GT(e)}function KT(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=eA(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function JT(e,t){return e<=t?"existing_only":"new_damage"}function ZT(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(qT(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return qT(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 XT(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function QT(e,t,r){const n=qT(r,1e3);if(0===n.length)return XT("mojibake");const o=void 0===e?[]:qT(e,Math.max(n.length,6));return{detector:"mojibake",outcome:JT(n.length,o.length),file:KT(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:ZT(n,o)}}function YT(e,t,r){const n=Ra(r);if(0===n)return XT("replacement_chars");const o=void 0===e?0:Ra(e);return{detector:"replacement_chars",outcome:JT(n,o),file:KT(e,o,t),afterCount:n,beforeCount:o}}function eA(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 tA=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 rA(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":tA.get(t)??"other"}const nA=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function oA(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:nA.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function sA(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:rA(t.path),encoding:eA(t.encoding),code_page:oA(t.pages),run_count:GT(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":VT(n)),before_count:VT(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}var iA=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 aA=(0,C.h)("LocalWriteExecutor"),cA=(0,E.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"]}),lA=async(e,t,r,n)=>{const o=setTimeout((()=>{aA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function uA(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function dA(e){try{return(await(0,Ys.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===el(e))return"missing";throw e}}async function hA(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await dA(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Ys.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 uA(e)}class pA{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,onWriteForAiTracking:i,writeFileMutationGuard:a,toolCallReads:c}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.onWriteForAiTracking=i,this.writeFileMutationGuard=a,this.toolCallReads=c}async execute(e,t){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Bp.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const r=(0,bi.o1)(t.path,this.workspacePath),n=this.toolCallReads,o=void 0!==n&&""!==t.toolCallId?n.take({toolCallId:t.toolCallId,resolvedPath:r}):void 0,s={writeStarted:!1},i=()=>{void 0===o||s.writeStarted||n?.restore(o)};try{const n=await this.executeWithRecord(e,t,r,o?.recorded,s);return gA(n)&&i(),n}catch(e){throw i(),e}}async executeWithRecord(e,t,r,n,o){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,i.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=fx(r,["assets","agent-tools","swarm-agents"]);if((0,bi.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:bi.PS})}});let h,p,f=!1;try{if((await(0,Ys.stat)(r)).size<=Ci){const e=await lA(c,"readText before write",3e3,(()=>ic(r,t.encodingHint)));h=e.text,p=e.encoding}else f=!0}catch{}const m=(await wx(r)).resolvedPath,g=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await lA(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,m,l)));if(g){const e=await lA(c,"handleBlockReason",3e3,(()=>hu(g,{onNeedsApproval:async(e,o)=>{const s="fileEdit"!==o?.type||o.isNewFile,i="fileEdit"===o?.type?o.diffString:l,a="fileEdit"===o?.type?o.blockReason:void 0;if(await ST(n,m))return fA(r);const c=await this.pendingDecisionProvider.requestApproval({type:$w.Write,details:{path:r,reason:e,isNewFile:s,diffString:i,before:h,after:l,blockReason:a},toolCallId:t.toolCallId});return c.approved?null:new Pr.v3({result:{case:"rejected",value:new Pr.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new Pr.v3({result:{case:"rejected",value:new Pr.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const w=await lA(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Ys.stat)(e)).isFile())return;const n=await(0,Ys.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!==w)return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:w})}});const y=(0,s.dirname)(m);if(await async function(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await ET(t)}catch{return!1}}(n,y))return fA(r);try{await lA(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=await hA(e,t),i=0;for(;ir)throw uA(e);try{await(0,Ys.mkdir)(a,{recursive:!1})}catch(r){const n=el(r);if("EEXIST"===n){if("directory"!==await dA(a))throw r;i+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(a);if(n===a||"missing"!==await dA(n))throw r;o=await hA(e,t),i=0;continue}throw r}i+=1}}(y)))}catch(e){const t=el(e);return"EACCES"===t||"EPERM"===t?new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:y,operation:"create_directory",error:"Permission denied"})}}):new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:tl(e)})}})}let v,b,S;if(void 0!==u)v=u,b=0;else{const e=await lA(c,"getBufferForWrite",3e3,(()=>cc(r,l,this.workspacePath,t.encodingHint)));v=e.buffer,b=e.lines,S=e.format.encoding}const k=()=>lA(c,"writeFile",3e3,(async()=>{if(await ST(n,m))throw new Error(CT(r));let e;c.signal.throwIfAborted(),o.writeStarted=!0,await async function(e,t,r){let n;try{n=await(0,Ys.open)(e,function(){const e=ti.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=el(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof ti.constants.O_NOFOLLOW}(t))throw new $T(e,`Refusing to write through a symlink at ${e}`);throw t}try{let o;try{o=(0,ti.realpathSync)(e)}catch{throw new $T(e,`Cannot verify canonical path before writing: ${e}`)}if(o!==e)throw new $T(e,`Refusing write: ${e} now resolves through a symlinked parent to ${o}`);if(!(await n.stat()).isFile())throw new $T(e,`Refusing to write to non-regular file at ${e}`);await n.truncate(0);const s=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i{try{await k()}catch(e){throw _=e,C=!0,e}};try{void 0===this.writeFileMutationGuard?await k():await this.writeFileMutationGuard.runExclusive(m,E)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!C||e!==_))return new Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof $T)return new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=el(e);return"EACCES"===t||"EPERM"===t?new Pr.v3({result:{case:"permissionDenied",value:new Pr.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===el(e)?new Pr.v3({result:{case:"noSpace",value:new Pr.bM({path:r})}}):"EDQUOT"===t?new Pr.v3({result:{case:"error",value:new Pr.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 Pr.v3({result:{case:"error",value:new Pr.QM({path:r,error:tl(e)})}})}if(this.fileChangeTracker&&void 0===u&&!d&&!f){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(r,h,l,e)}if(this.onWriteForAiTracking&&void 0===u&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:h,afterContent:l,metadata:e})}catch(e){aA.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const x=v.byteLength;let P;if(void 0!==u||f||d||this.recordEncodingChecks(c,r,h,p,l),t.returnFileContentAfterWrite)try{P=await lA(c,"readText after write",3e3,(()=>sc(r,t.encodingHint)))}catch{}return new Pr.v3({result:{case:"success",value:new Pr.j6({path:r,linesCreated:b,fileSize:x,...void 0!==P&&{fileContentAfterWrite:P}})}})}catch(e){a.error=e,a.hasError=!0}finally{iA(a)}}recordEncodingChecks(e,t,r,n,o){try{const s={path:t,encoding:n,pages:$l.pages()};for(const t of function(e,t,r){return[QT(e,t,r),YT(e,t,r)]}(r,n,o))cA.increment(e,1,sA(t,s))}catch(t){for(const t of zT)cA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});aA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}}}function fA(e){return new Pr.v3({result:{case:"error",value:new Pr.QM({path:e,error:CT(e)})}})}class mA extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function gA(e){return"error"===e.result.case&&e.result.value.error===CT(e.result.value.path)}const wA=(0,C.h)("local-exec:provider"),yA=new Set,vA=new ml.AsyncLocalStorage;class bA extends te{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of yA)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of yA)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,ti.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,ri.$6)(n);return(0,ri.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.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,ri.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});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 lu(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,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new du(c,this.askpassConfig)),this.shellManager&&(c=new uu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uT(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(Ir,jI(l)),this.register(_r,jI(new AI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bT,d=e.overrideWriteExecutor??new pA(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u});this.register(Tr,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(gA(e))throw new mA(e);return e}))},jI(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof mA)return e.result;throw e}}}}(d));const h=e.overrideDeleteExecutor??new Dw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking);this.register(ge,jI(h)),this.register(ve,jI(new Lw)),this.register(be,new TR);const p=this.mcpStateAccessor??new oT(this.mcpLease),f=e.overrideGrepExecutor??new wI(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:p,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep});this.register(Se,jI(f));const m=e.overrideReadExecutor??new kT(new VP(this.permissionsService,a,{mcpStateAccessor:p,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),u,this.permissionsService,a),g=new cr(m);this.register(lr,g),e.registerRedactedReadExecutor&&this.register(ur,g);const w=e.overrideLsExecutor??new _I(this.permissionsService,this.ignoreService,a);this.register(Dt,jI(w)),this.register(we,jI(new KI(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(fe,jI(new BI(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Gt,jI(new kr(new uE(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(lr))))),this.register(Vt,jI(new dE(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Kt,jI(new hE(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(Jt,jI(new iT(p,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const y=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(p,t,e),v=jI({execute:(e,t,r)=>{const n=vA.getStore();return void 0!==n&&(n.ran=!0),y.execute(e,t,r)}});this.register(Fr,{execute:async(t,r,n)=>{const o={ran:!1},s=await vA.run(o,(()=>v.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 p.getState(t),l=eT(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tT(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=[],wA.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Tu(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(le,jI(this.backgroundShellExecutor)),this.shellStreamExecutor=new yT(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(Rr,function(e,t){const r=new ei.q({max:10,ttl:t?.ttl});return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=NI(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new FI(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor)),void 0!==e.agentStoreConflictDrainer&&this.register(ae,new DI(e.agentStoreConflictDrainer)),this.register(jr,new hT(this.permissionsService)),this.register(Zt,new $R(this.permissionsService)),this.register(_n,new TT(this.permissionsService));const b=new pT(this.shellStreamExecutor);this.register(Lr,jI(b));const S=!1===e.enableWriteBackgroundShellStdin?new OI((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OI(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(ue,jI(S)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(me,jI(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new UR({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Or,jI(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aT(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,bi.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,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,onRequestContext:r.onRequestContext});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,yA.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}getRecordScreenExecutor(){return this.recordScreenExecutor}withPendingShells(e){return new re(e,[Y(Rr,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.rebuildRequestContextOnRulesChange&&(yA.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 SA(e){return e.replace(/\\/g,"/")}function kA(e,t){for(const r of t){const t=SA(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var _A;function CA(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return _A.Plugin;const n=SA(e.fullPath);return kA(n,r.builtinDirs)?_A.Builtin:Um(e.fullPath,t).inAgentStore?_A.UserStore:kA(n,r.userDirs)?_A.UserHome:(kA(n,r.workspaceDirs),_A.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"}(_A||(_A={}));var EA=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 xA=(0,ha.debuglog)("merged-agent-skills"),PA=(0,C.h)("merged-agent-skills");class IA{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,i.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(xA("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 PA.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}}},[a,c]=await Promise.all([Promise.all(n),o()]),l=a.flat(),u=this.getPromptSortContext?.(),d=Wm(l,u??jm);let h=d;return c.ok?c.paths.length>0&&(h=d.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,c.paths)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(RA));var t})),void 0!==u?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:CA(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(h,u):h}catch(e){t.error=e,t.hasError=!0}finally{EA(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()}),IA.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()}}IA.CHANGE_COALESCE_MS=1500;const RA=`/${mm.configDir}/${mm.subdir}/`,TA=(0,C.h)("skill-sync-manifest"),AA=".sync-manifest.json";async function $A(e,t){try{const r=await(0,Ys.readFile)((0,s.join)(e,AA),"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:(TA.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===el(r)||TA.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function MA(e,t,r){e.skills[t]={lastSyncedAt:r}}function DA(e,t){delete e.skills[t]}var OA=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 FA=(0,C.h)("builtin-skills-sync");function NA(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jA(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 LA(e){const t=qp(e.content),r=NA(t.data)?t.data:{};return zp(`${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={...NA(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 UA(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 BA(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,Ys.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,Ys.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Ys.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,Ys.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Ys.writeFile)(t,r,"utf-8")}try{await(0,Ys.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==el(e))throw e}try{await(0,Ys.rename)(n,r)}catch(e){throw i&&(await(0,Ys.rename)(o,r),i=!1),e}i&&(await(0,Ys.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Ys.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Ys.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===el(t)||FA.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Ys.mkdir)(n,{recursive:!0}),await(0,Ys.writeFile)(o,i,"utf-8"),!0}async function BA(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Ys.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===el(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await BA(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function WA(e,t){try{return(await(0,Ys.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===el(r)||FA.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function HA(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const a=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,i.VI)(e.withName("syncBuiltinSkills")),!1).ctx,c=Date.now(),l=t.skillDir??bm((0,o.homedir)()).dirPath;await(0,Ys.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([$A(l,a),WA(a,l)]),h=u.lastInventoryAt;(void 0===h||c-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([qA((0,s.join)(r,"SKILL.md")),"canvas"===e?qA((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}})));FA.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){FA.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(a,l,d,u),u.lastInventoryAt=c);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):FA.warn(a,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:(t.canvasKit,km((0,o.homedir)()).dirPath),m=void 0!==f&&await qA((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?c-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,i=void 0!==t&&Ud(t,"local"),d=void 0!==t&&!i,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&i)jA(t),f!==l&&await(0,Ys.mkdir)(f,{recursive:!0}),await UA(a,f,{id:e,fileContent:LA(t),resources:t.resources??{}})?v++:b++,MA(u,e,c);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Ys.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),DA(u,e),h&&(S.push(e),FA.info(a,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?c-r.lastSyncedAt:null}))}else r||MA(u,e,c)}catch(t){FA.warn(a,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),n=(0,s.join)(e,AA);await(0,Ys.mkdir)(e,{recursive:!0}),await(0,Ys.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,Ys.rename)(r,n)}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===el(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?FA.warn(a,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):FA.debug(a,"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{OA(r)}var n}async function qA(e){try{return await(0,Ys.stat)(e),!0}catch(e){const t=el(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const zA=(0,C.h)("managed-skills-sync");function GA(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 VA{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(...rh(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=GA(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var KA=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 JA(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class ZA{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??Au,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: ${tl(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: ${tl(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(Gf));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Gf(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=JA(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 qf({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${tl(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,Ys.realpath)(r);if(!(await(0,Ys.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,Ys.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 Uf(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}: ${tl(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,ye.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,i.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(),a=JA(this.marketplaceOptions,this.userHomeDirectory),c=o.importThirdPartyPlugins,l=o.loadUserLocalPlugins??!0,u=o.loadCursorFirstParty??a.length>0;if(!c&&!u&&!l)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 d=(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??Au,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(Hf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>qf({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Au,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,Ys.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,Ys.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,Ys.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{op(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Ys.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 Uf(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,Ys.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=zf(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=>zf(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:c,loadUserLocal:l,loadCursorFirstParty:u&&a.length>0,marketplaceSources:a.length>0?a.map((e=>({...e,onCursorError:d}))):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: ${tl(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{KA(e)}}}var XA=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function QA(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function YA({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||FE(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class e${constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new XA.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new XA.aYW({}))}}function t$(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 r${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 n${constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new r$((()=>this.fetchSettings())),this.hostMcpBridgeClients=new WeakSet,this.teamRepos=new r$((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new r$((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){const e=this.settingsGeneration;try{const t=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e>=this.lastFetchedGeneration&&(this.lastFetchedSettings=t,this.lastFetchedGeneration=e),t}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){return this.settings.get().catch((()=>{}))}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(n){if(function(e,t){return!my(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,hy.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=YA({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?YA({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}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,hy._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=QA(t.url);return void 0!==n&&r.some((e=>QA(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}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=LE({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===XA.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===XA.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===XA._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===XA.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:t$(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 o$=new ry,s$={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Vc((0,ye.q6)(),o$,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?Qs(r):void 0),workspaceRoots:n,createdAt:new Date}}},i$=(0,C.h)("ControlledConversationActionManager");class a${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,P.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 qr.QFf({action:{case:"cancelAction",value:new qr.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 P.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 P.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 P.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 P.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,P.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new qr.QFf({action:{case:"userMessageAction",value:new qr.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){i$.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof P.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 P.W2("ControlledConversationActionManager disposed")))}}var c$=r("../cursor-sdk-local-runtime/dist/utils/logger.js");const l$="x-blob-encryption-key";function u$(e,t){const r={...t};return void 0!==r[l$]||(0,Tn.TU)(e)&&(r[l$]=e),r}const d$=new Map;function h$(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function p$(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 f$(e){return new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:e})})}})}function m$(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function g$(e){e?.catch((e=>{c$.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const w$=new Set(["mcp.slack.com","setup.shopify.com"]);async function y$(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!==(i=e,a=r.restMcpHost,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?Wv(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!w$.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await _b(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===Sb(t.CLIENT_ID)?{...c,...t,CLIENT_ID:c.CLIENT_ID}:{...c,...t}:c:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}class v${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 y$(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class b${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 S${constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class k${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 vy(t,n.configPath??"another config")}return await o(e,r)}}class _${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={};for(let e=0;e({prefix:t,scope:r,fileSource:new P_(e,"enterprise"===r||"env"===r?sv:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new b$(t,l),p=new S$(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,iv.indexOf(t)0?[new k$(f)]:[]],g=new I_(u?new v$(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new _$(y)}static init(e,t,r,n=!1,o,i={}){const a=new N_(s.join(r,"mcp-auth.json"));(async function(e){await(0,Ys.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new ky(s.join(r,"mcp-approvals.json"),t);return new C$(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 E$="cursor-plugins/local";function x$(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===E$)return r}class P$ extends u_{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class I${constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Ys.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,Ys.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Ys.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class R${constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return c$.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&D$(r))continue;const e=M_(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}}):c$.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 T${constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:M$(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function A$(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};return{async createLease(a){const c=a.workspaceState,l=c.projectRoot??c.workingDirectory,u=c.projectDirectory;if(!l||!u)return new l_;const d=new I$((0,s.join)(u,"mcp-disabled.json")),h=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return C$.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new N_((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new ky((0,s.join)(n,"mcp-approvals.json"),r),p=[new Ey,new Sy(h),new A_(t),new by(a)],f=[];return c&&f.push({prefix:"",loader:new $_((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new $_((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),$$(f)}({teamSettingsService:t,projectRoot:l,projectDirectory:u,ignoreApprovals:r,disabledStore:d,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),p=[],f=e.inlineMcpServers??{};if(Object.keys(f).length>0){const e=new N_((0,s.join)(u,"mcp-auth.json")),r=[new Ey,new A_(t)];p.push({prefix:"",loader:new I_(new T$(f),e,r,i)})}const m=x$(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new ky((0,s.join)(u,"mcp-approvals.json"),l),o=new N_((0,s.join)(u,"mcp-auth.json")),a=[new Ey];r||a.push(new Sy(e)),a.push(new A_(t),new by(d));const c=new VA(m.pluginsService),h=new I_(new R$(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new l_;const g=$$(p),w=await g.load(e.initializationCtx??(0,ye.q6)(),e.cache);return new P$(w)}}}function $$(e){return 1===e.length?e[0].loader:new _$(e)}function M$(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 D$(e){return"claude-plugin"===e.pluginSource}function O$(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function F$(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class N${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>N$.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===Tr.symbol||e===ge.symbol?{kind:"path"}:e===Ir.symbol||e===Rr.symbol||e===le.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=F$(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===Rr.symbol&&O$(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new xr.FI({event:{case:"hookContext",value:new xr.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===Tr.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=F$(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 j$(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}N$.CARRIERS_BY_EXEC_ID_MAX=32,Error,bl.execFileSync,new Map,ti.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 L$=["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(j$);function U$(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(B$,"\n\n"):r).trim()}(e,L$)}["system_reminder","system-reminder"].map(j$);const B$=/\n{3,}/g;function W$(e){const t=(0,Zs.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,Zs.sh)(e.parentConversationId);return`${Zs.O2}/${r}/subagents/${t}.${e.ext}`}return`${Zs.O2}/${t}/${t}.${e.ext}`}function H$(e){const t=(0,Zs.sh)(e.conversationId);return`${Zs.O2}/${t}.${e.ext}`}function q$(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(W$({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(W$({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(H$({conversationId:e.conversationId,ext:n}));return n}var z$;(()=>{const e=globalThis.Intl?.Segmenter;e&&new e(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(z$||(z$={}));var G$=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},V$=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 K$(e){switch(e){case qr.xyI.AGENT:return"agent";case qr.xyI.ASK:return"ask";case qr.xyI.PLAN:return"plan";case qr.xyI.DEBUG:return"debug";case qr.xyI.TRIAGE:return"triage";case qr.xyI.MULTITASK:return"multitask";case qr.xyI.CUSTOM:return"custom";case qr.xyI.UNSPECIFIED:default:return"agent"}}function J$(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 Z$(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 X$=new TextEncoder,Q$=new TextDecoder,Y$=new class{serialize(e){const t=JSON.stringify(e,J$);return X$.encode(t)}deserialize(e){const t=Q$.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Z$):JSON.parse(t)}};function eM(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function tM(e){return"system"!==e.role&&!eM(e)}function rM(e,t){return"user"===e.role&&"user"===t.role}async function nM(e,t,r){const n=await t.getBlob(e,r);return n?qr.Anz.fromBinary(n).summarizedMessages:[]}async function oM(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=Y$.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 sM(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 oM(e,t,o,n);r&&n.messages.push(r)}return n}async function iM(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=oM(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 cM(e){return U$(e)}const lM=/[\s\S]*?<\/think>/gi,uM=/[\s\S]*?<\/thinking>/gi,dM=/\n{3,}/g;function hM(e){let t=e;return t.includes("<")&&(t=t.replace(lM,"").replace(uM,"")),(t.includes("\n\n\n")?t.replace(dM,"\n\n"):t).trim()}function pM(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?cM(e):e;return r?hM(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=hM(t?cM(e.text):e.text);return aM({...e,text:r},!1)}return aM(e,t)})).filter(Boolean).join("\n")}function fM(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?cM(n):n,s="assistant"===e.role?hM(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?cM(r.text):r.text,s="assistant"===e.role?hM(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 mM(e){return e.endsWith("\n")?e:`${e}\n`}function gM(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 wM(e){if("system"===e.role||eM(e))return;const t=fM(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 yM{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=W$({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=G$(o,(0,i.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=gM(n),{appendFile:a,streamFullJsonlWrites:c,writeJsonl:l,writeText:u,writeJson:d}=this.options;if(a&&c&&l&&!u&&!d&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:a,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const h=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=G$(n,(0,i.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const a=(0,i.OA)(o.ctx),c=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await nM(a,t,e);return s+=r.length,await sM(a,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of g)c.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",l),o.span.setAttribute("hydratedBlobBytes",u),o.span.setAttribute("largestHydratedBlobBytes",d),o.span.setAttribute("totalDeserializeDurationMs",h),o.span.setAttribute("omittedOversizeBlobCount",p),o.span.setAttribute("omittedOversizeBlobBytes",f),o.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=G$(n,(0,i.VI)(e.withName("hydratePromptMessages")),!1),y=await sM(a,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const v=y.messages.filter(tM);return c.push(...v),c}catch(e){n.error=e,n.hasError=!0}finally{V$(n)}}(s.ctx,this.blobStore,t);if(0===h.length&&0===o.jsonlLines.length)return!0;let p;if((this.options.writeText||e)&&(p=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=pM(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(h)),this.options.writeText){const e=p??"",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=fM(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(h);if(e||o.jsonlLines.length>0){const n={mode:K$(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&&rM(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=wM(e);t&&r.push(t)}return r.join("\n")}(h);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&p?.trim())try{const t=(await e(p)).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"),mM(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{V$(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,a=0,c=0;const l=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===a?await this.writeFile(r,e):await n(r,e),a++,c+=e.length},u=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await l())};let d,h=0;const p=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 nM(e,t,s)}catch{continue}await iM(e,t,r,o,{skipFailedReads:!0,visit:n})}return await iM(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{tM(e)&&await n(e)}}),o}((0,i.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(h++,1!==h?(2===h&&d&&(rM(d,e)||await u(wM(d)),d=void 0),await u(wM(e))):d=e)}));d&&await u(wM(d));for(const e of t.terminalLines)await u(e);await l(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",a),e.span.setAttribute("writtenChars",c),e.span.setAttribute("hydratedBlobCount",p.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",p.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",p.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",p.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",p.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",p.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",p.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const a=t.rootPromptMessagesJson.length,c=gM(o),l=c.jsonlLines.length>0;if(a===n&&!l&&!o.overviewFactory)return a;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&a>=n&&(a>n||l))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?a:0;const d=G$(s,(0,i.VI)(e.withName("writeFromStateIncremental")),!1);if(a===n&&l)try{return await u(this.resolveFilePath(r,"jsonl"),mM(c.jsonlLines.join("\n"))),a}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)?a:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await sM(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=wM(e);t&&s.push(t)}if(s.push(...c.jsonlLines),s.length>0){const e=mM(s.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}return a}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)?a:0:0}}catch(e){s.error=e,s.hasError=!0}finally{V$(s)}}}function vM(e){return Object.values(ke).some((t=>t===e))}function bM(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 SM(e){return Ve(e)?`prompt:${e.prompt}`:`command:${e.command}`}function kM(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class _M{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(SM(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=SM(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(!Ae(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ae(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in _e&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ae(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=Ne(r,this.logger),o=St(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=St(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,...kM(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))vM(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))vM(e)&&t.add(e);return t}}const CM="Read",EM="Write",xM="Delete",PM="List",IM="Grep",RM="Shell",TM="ReadLints";function AM(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const $M=new Set([CM,EM,xM,PM,IM,TM]);function MM(e){const t=AM(e,"tool_name"),r=[AM(e,"file_path"),"string"==typeof t&&$M.has(t)?AM(AM(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const DM=(0,C.h)("cli-hooks-executor");function OM(e){try{return(0,ti.statSync)(e).isFile()}catch{return!1}}const FM="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function NM(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function jM(e,t){const r=NM(e,t);if("string"==typeof r||null===r)return r}class LM{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,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,oh.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,Zs.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=q$(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,Ys.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,Zs.Rv)((0,o.homedir)(),this.workspacePath),n=q$({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Ys.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,...kM(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?We(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?We(n,t):n).some((e=>Ke(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=NM(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 Qe.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===ke.subagentStop){const e=jM(t,"subagent_id"),r=jM(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:[this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===ke.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return Be(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=Be(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 Be(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return Be(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=We(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)Ve(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):Ke(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,bi.o1)(t,r),[o,i,a]=await Promise.all([(0,bi.DN)(n),(0,bi.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,bi.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:MM(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===ke.stop||e===ke.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 We(n,u))Ke(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=je(`Hook execution failed: ${n}`),r=ot(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return DM.warn((0,ye.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;if(1===t.length)return t[0];const r=Xe.includes(e),n=e===ke.sessionStart,o=e===ke.workspaceOpen,s=Ge.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=Ye(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?et(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=Ye(i[e],l)}var a,c;return i}(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=ot(e,je(`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=ot(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=ot(e,je(`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=ot(e,je(`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=st(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=st(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=rt({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+FM}),{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+FM}),{success:!1,source:s,index:i})}const y=Ze(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=rt({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,ye.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 tt(e)?nt(0,{permission:"allow"}):e===ke.beforeSubmitPrompt||e===ke.sessionStart?nt(0,{continue:!0}):e===ke.stop?nt(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=ot(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=ot(e,je(`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=wt.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:OM}):t.command;let w;if(m)w=e?yt(g):g;else if("windows_temp_file"===f){d=await(0,Ys.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Ys.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 | ${yt(t)} }`+gt(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+gt(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=jM(n,"conversation_id")??void 0,v=jM(n,"session_id")??void 0,b=jM(n,"transcript_path"),S=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),k=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:S?.at(-1)??y:v,_=this.buildHookEnvironment({transcriptPath:b,sessionId:k,conversationId:y,executionEnv:i}),C={};for(const[e,t]of Object.entries(_))void 0!==t&&(C[e]=t);void 0!==a&&(C.CURSOR_PLUGIN_ROOT=a,C.CLAUDE_PLUGIN_ROOT=a);const E=(0,ye.q6)(),x=new xc.StringDecoder("utf8"),P=new xc.StringDecoder("utf8");let I,R="",T="",A=null,$=!1;for await(const e of this.shellExecutor.execute(E,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:C,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),$=!0);break;case"stdout":R+=x.write(e.data);break;case"stderr":T+=P.write(e.data);break;case"exit":A=e.code,I=e.aborted}if(R+=x.end(),T+=P.end(),m&&!$)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const M=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:R,stderr:T,exitCode:A,duration:M}}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,Ys.rm)(d,{recursive:!0,force:!0})}catch{}}}}class UM{constructor(e){this.config=e,this.configuredSteps=_M.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var BM=r("node:perf_hooks");function WM(e,t){void 0!==e&&t.length>0&&e.push(...t)}class HM 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 qM=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function zM({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 HM({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new qM.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ge).map((e=>{if(!function(e){return e===ke.sessionStart||e===ke.beforeSubmitPrompt||e===ke.preToolUse||e===ke.postToolUse||e===ke.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}]})));class GM extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class VM extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const KM="To view or modify configured hooks, go to Cursor Settings > Hooks.";function JM(e,t){return Ue(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${KM}`)}function ZM(e){return function(e){return e instanceof GM}(e)||function(e){return e instanceof VM}(e)}const XM=(0,C.h)("generic-hooks");function QM(e,t,r,n){try{return zM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof HM)return XM.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const YM=e=>Math.round(1e3*e)/1e3;function eD(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,Js.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 wl(e.signal,(()=>t.executeHookForStep(ke.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));WM(i,QM(e,r,ke.postToolUseFailure,h?.additional_context))}catch(t){XM.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await wl(e.signal,(()=>t.executeHookForStep(ke.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));WM(i,QM(e,r,ke.postToolUse,u?.additional_context))}catch(t){XM.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 tD(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await wl(e.signal,(()=>r.executeHookForStep(ke.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=Ue(r);try{WM(n.hookContextCollector,zM({hookEventName:ke.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof HM))throw t;XM.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))),WM(n.hookContextCollector,zM({hookEventName:ke.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(ke.preToolUse,s.toolName)??!1,c=n instanceof HM;if(a){const e=je(`${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}}XM.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(ZM(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 rD(e){return e.toolCallId}function nD(e,t,r,n){return{async execute(o,s,i){const a=sD(o,t),{hookContext:c,helpers:l}=eD(o,s,a,r,n,i);let u;try{u=await tD(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=BM.performance.now();try{const t=await e.execute(o,s,i),r=YM(BM.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(ZM(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);XM.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=YM(BM.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*oD(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function sD(e,t){const r=Et(e),n=e.get(_t);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===ke.preToolUse||e===ke.postToolUse||e===ke.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 iD(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class aD{async readFile(e){try{return await Ys.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Ys.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,Ys.lstat)(e)).isSymbolicLink())return!0}catch(e){if(iD(e))return!0;throw e}return!1}(e,t)}}class cD{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 Nr.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 Nr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Nr._G({result:{case:"success",value:new Nr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function lD(e){return!!e&&e.type!==Bi.vc.INSECURE_NONE&&e.type!==Bi.vc.UNSPECIFIED}async function uD({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(ke.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=JM("Command execution",i.user_message);throw new GM(e)}if("ask"===i?.permission)return a=i.user_message,new xr.In({kind:xr.b.FORCE_PROMPT,reason:a});var a}const dD={toolName:RM,getToolCallId:rD,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 Cr.Lt({result:{case:"rejected",value:new xr.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=lD(r.sandboxPolicy);xt(t,ke.beforeShellExecution)&&Ur(r,await uD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class hD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,dD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const pD={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Cr.nt({result:{case:"error",value:new Cr.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 fD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,pD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const mD={toolName:"ComputerUse",getToolCallId:rD,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ag.ks({result:{case:"error",value:new Ag.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 gD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,mD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const wD={toolName:xM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Er.Pi({result:{case:"rejected",value:new Er.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 yD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,wD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const vD={toolName:TM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new UI.Ek({result:{case:"rejected",value:new UI.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 bD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,vD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const SD={toolName:"Fetch",getToolCallId:rD,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Nw.uN({result:{case:"error",value:new Nw.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 kD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,SD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _D={toolName:IM,getToolCallId:rD,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 oy.Ud({result:{case:"error",value:new oy.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 CD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,_D)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ED={toolName:PM,getToolCallId:rD,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 bI.fv({result:{case:"rejected",value:new bI.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 xD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,ED)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PD=(0,C.h)("hooks-exec:mcp");function ID(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(ID):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&ID(e))))}function RD(e,t,r,n){try{return zM({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof HM)return PD.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class TD{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(ke.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(ke.beforeMCPExecution)))return new er.iz({result:{case:"error",value:new er.Nh({error:`"${dr}" 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=sD(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,Js.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(ke.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{WM(i,zM({hookEventName:ke.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof HM))throw t;PD.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 er.iz({result:{case:"permissionDenied",value:new er.HQ({error:JM("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(!ID(n))throw new TypeError("updated_input value is not JSON");t.args[e]=sr.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){PD.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}WM(i,zM({hookEventName:ke.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(ke.preToolUse,c)??!1,l=t instanceof HM;if(r){const r=je(`${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 er.iz({result:{case:"permissionDenied",value:new er.HQ({error:JM("MCP tool execution",r),isReadonly:!1})}})}PD.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=xt(e,ke.beforeMCPExecution)?await n.executeHookForStep(ke.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=JM("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new er.iz({result:{case:"permissionDenied",value:new er.HQ({error:t,isReadonly:!1})}})}const g=BM.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=YM(BM.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){PD.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(ke.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 er._Z({content:{case:"text",value:new er.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 er._Z({content:{case:"text",value:new er.zN({text:String(e.text)})}})):t.push(new er._Z({content:{case:"text",value:new er.zN({text:JSON.stringify(e)})}}))}else t.push(new er._Z({content:{case:"text",value:new er.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new er.iz({result:{case:"success",value:new er.QW({content:t,isError:r})}})}catch(t){return PD.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=YM(BM.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(ke.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return WM(c,RD(e,n,ke.postToolUse,l?.additional_context)),l}catch(t){return void PD.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(ke.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});WM(u,RD(e,n,ke.postToolUseFailure,d?.additional_context))}catch(t){PD.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const AD={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new er.kP({result:{case:"error",value:new er.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 $D{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,AD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const MD={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 er.ZD({result:{case:"error",value:new er.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 DD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,MD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OD={toolName:CM,getToolCallId:rD,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new tr.sV({result:{case:"rejected",value:new tr.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?.(ke.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${KM}`}(t,e instanceof Error?e.message:String(e));throw new VM(r,e)}}((()=>o.executeHookForStep(ke.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=JM("File read",a.user_message);throw new GM(e)}}};class FD{constructor(e,t,r){this.wrappedExecutor=new cr(nD(e,t,r,OD))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ND={toolName:"RecordScreen",getToolCallId:rD,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new MR.Tj({result:{case:"failure",value:new MR.yH({error:t})}}),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 jD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,ND)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function LD(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const UD={toolName:RM,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 xr.W4({result:{case:"rejected",value:new xr.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:LD(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||"";xt(t,ke.beforeShellExecution)&&Ur(r,await uD({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:lD(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=LD(r);await o.executeHookForStep(ke.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:lD(t.requestedSandboxPolicy),tool_use_id:i})}};class BD{constructor(e,t,r){this.wrappedExecutor=nD(e,t,r,UD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class WD{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 HD={toolName:RM,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 xr.FI({event:{case:"rejected",value:new xr.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new xr.FI({event:{case:"hookContext",value:new xr.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new WD,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=lD(r.requestedSandboxPolicy);xt(t,ke.beforeShellExecution)&&Ur(r,await uD({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=lD(t.requestedSandboxPolicy);await n.executeHookForStep(ke.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class qD{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=sD(o,t),{hookContext:c,helpers:l}=eD(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await tD(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of oD(n,c))yield e;return}const h=BM.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=YM(BM.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of oD(n,c))yield e;throw e}const f=YM(BM.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){XM.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 oD(n,c))yield e}}}(e,t,r,HD)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class zD{constructor(e,t,r){const n=new Map;this.wrappedExecutor=nD(e,t,r,function(e){return{toolName:EM,getToolCallId:rD,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 Pr.v3({result:{case:"error",value:new Pr.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?.(ke.afterFileEdit))return;let s,i=!1;try{(await(0,Ys.stat)(r.path)).size>262144?i=!0:s=await sc(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?.(ke.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,ax.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(ke.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await sc(e),r=ma(t),o=Buffer.byteLength(t,"utf8");return new Pr.v3({result:{case:"success",value:new Pr.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 GD(e,t,r){return t===e.symbol}function VD(e,t,r){return GD(Ir,e)?new BD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Rr,e)?new qD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Tr,e)?new zD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Gt,e)?new TD(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):GD(lr,e)||GD(ur,e)?new FD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Dt,e)?new xD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Se,e)?new CD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ve,e)?new kD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ge,e)?new yD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(we,e)?new bD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Vt,e)?new $D(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Kt,e)?new DD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(le,e)?new hD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(ue,e)?new fD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(me,e)?new gD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Or,e)?new jD(t,r.hookExecutor,r.baseHookRequestExtractor):GD(Fr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new cD(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class KD{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===Pt.symbol)return new $t(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=VD(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=VD(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=Pt;yield[e,new $t(this.hookExecutor)]}}const JD={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ZD(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>ZD(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,ri.oG)(),args:[...dt,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,bl.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}}}function XD(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function QD(e){return"string"==typeof e&&e.length>0?e:void 0}function YD(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function eO(e){if(Array.isArray(e)&&e.every(YD))return e.map((e=>({id:e.id,value:e.value})))}class tO{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 rO(e,t={}){const r=await new _M(new aD,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?bM():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 UM(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...JD,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new LM(r,i,a,(t.createTerminalExecutor??ZD)(),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 nO(e={}){return{createHooksRuntime:t=>rO(t.workspaceState,e)}}var oO=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function sO(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function iO(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 ry,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,Dn.createClient)(oO.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await HA(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return zA.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,ye.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new XA.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:pO(),getAgentSkills:async e=>[]};const p=(0,ye.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=aO(t);return{getAllCursorRules:async t=>cO(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?pO():1===m.length?m[0]:new mg(m,(()=>jm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=aO(t);return{getAllCursorRules:async t=>cO(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>cO(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new wg(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 Pg(e,t))):[],v=0===y.length?new Sg:1===y.length?y[0]:new Rg(y),b=x$(o.services.pluginBootstrapOutputs),S=b&&a?new vg(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new Tg((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,_=new mg([g,w,...S?[S]:[]],(()=>jm)),C=new IA([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),E=new Rg([v,...k?[k]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:S,pluginSubagentsService:k,mergedCursorRulesService:_,mergedAgentSkillsService:C,mergedSubagentsService:E};const x={cursorRulesService:_,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:E};return x},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 sO(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function aO(e){const t=Promise.all(e.allowedRoots.map(dO)),r=Promise.all(e.excludedRoots.map(dO));return async e=>{const[n,o,s]=await Promise.all([hO(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>lO(n,e)))&&o.some((e=>lO(n,e)))}}async function cO(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function lO(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function uO(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function dO(e){try{return uO(await(0,Ys.realpath)(e))}catch{return uO(e)}}async function hO(e){try{return uO(await(0,Ys.realpath)(e))}catch{return}}function pO(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function fO(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":c$.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":c$.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){c$.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=mO(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 am(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,Dn.createClient)(oO.I,e.dashboardTransport),n=Up((async()=>{try{return await r.getEffectiveUserPlugins(new XA.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Up((async()=>{if(void 0===o)return{plugins:[]};try{const e=await am(o);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||rm(t)})).map((({key:e,entry:t})=>{const r=cm(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 i=[];if(n.length>0)try{const e=n.map((e=>{const t=cm(e.key);return new XA.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new XA.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new dh(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new dh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=mO(d),p=new ZA(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:E$,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)c$.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)c$.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 mO(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class gO{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const wO=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function yO(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 vO(e){const t=yO(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function bO(e){const t=yO(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 SO(e){const t=vO(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>vO(t.host).length-vO(e.host).length));for(const e of r){const r=vO(e.host);if(t===r)return bO({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return bO({reportedWorkspacePath:e.reported,suffix:n})}}}const kO={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class _O extends bA{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await sO(this.sessionMcpLease)}}}function CO(e){const t=new ry;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 gO,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new l_,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 l_:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Fw(u,d):new Ow(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 kO;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return kO}}(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),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 bA(u):new _O(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Fr);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(Fr,{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=>SO({value:e,roots:o})??e));for(const e of wO){const t=n[e];if(void 0===t||""===t)continue;const r=SO({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??yO(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 sO(c),e}}}}const EO=["cursorRulesService","getAgentSkills","subagentsService"],xO=new WeakSet;function PO(e){("object"==typeof e&&null!==e||"function"==typeof e)&&xO.add(e)}function IO(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&xO.has(e)}function RO(e,t){const r=Object.keys(t).filter((e=>!EO.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${EO.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of EO)Object.hasOwn(t,r)&&(e[r]=t[r])}async function TO(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&&(PO(s.cursorRulesService),PO(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&RO(n,e)}return n}catch(t){try{await AO(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 AO(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await sO(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||IO(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||IO(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 sO(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 $O=["project","user","team","mdm","plugins"],MO=new Set([...$O,"all"]);function DO(e){if(void 0===e||0===e.length)return FO([]);for(const t of e)if(!MO.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{...FO($O),all:!0}}return FO(e.filter((e=>"all"!==e)))}function OO(e,t){return e[t]}function FO(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 NO=Object.freeze({}),jO=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:NO});async function LO(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 sO(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function UO(e={}){const t=function(e={}){return{workspace:e.workspace??s$,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({...jO.metadata,...e.metadata}),r={...jO,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await TO(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,Mn.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 LO(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 LO(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 TO(t,r,n);s?await AO(i,{disposeLocalExtensibility:l}):(o=i,await AO(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await AO(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class BO{async requestApproval(e){return{approved:!0}}}class WO{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 HO{async open(e,t){}async getDiagnostics(e,t){return[]}}class qO{async getCodebaseReference(e,t){}}class zO{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class GO{constructor(e){this.subagents=e.map((e=>new gn.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:gn.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}let VO;function KO(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Qs(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,Zs.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,ti.statSync)(e).isDirectory()&&((0,ti.accessSync)(e,ti.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,Zs.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,Zs.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===VO&&(VO=function(e){return(0,ti.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),VO)})}async function JO(e,t){const r=(0,s.dirname)(e);await(0,Ys.mkdir)(r,{recursive:!0}),await(0,Ys.writeFile)(e,t,"utf-8")}class ZO{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=KO(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=W$({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new yM(this.projectDir,e.blobStore,JO,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new yM(this.projectDir,e.blobStore,JO,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=W$({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){c$.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,Tn.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=W$({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=W$({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(KO(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const XO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,QO="User aborted/interrupted manually.";class YO{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.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,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 Sn}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(!XO.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&kn(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,Mn.C)(),o=function(e){const t=new Tn.We,r=(0,Tn.sh)(e),n=new Tn.pH(new Tn.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 ZO({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:gn.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:gn.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 mn.a3({status:mn.jh.ACCEPTED}):new mn.a3({status:mn.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){c$.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 mn.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,Mn.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}async executeSubagentOnce(e,t,r,n){let o,s=0;const i=new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:r.prompt})})}}),a=new qr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new a$,l={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&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return en(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return rn(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return sn(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new $o.tz({result:{case:"rejected",value:new $o.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return nn(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},u={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const d=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==d&&""!==d?d:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new re(f,function(e){const t=[Y(Tr,$r(e.errorMessage)),Y(ge,Mr(e.errorMessage)),Y(Gt,Dr(e.errorMessage))];return e.wrapShell&&t.push(Y(Ir,function(e){return{execute:async(t,r)=>new xr.W4({result:{case:"permissionDenied",value:Ar(e,r)}})}}(e.errorMessage)),Y(Rr,function(e){return{async*execute(t,r){yield new xr.FI({event:{case:"permissionDenied",value:Ar(e,r)}})}}}(e.errorMessage)),Y(le,function(e){return{execute:async(t,r)=>new Cr.Lt({result:{case:"permissionDenied",value:Ar(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(Y(ue,function(e){return{execute:async(t,r)=>new Cr.nt({result:{case:"error",value:new Cr.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})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),i,a,l,m,n.agentStore.getBlobStore(),c,u,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:u$(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:QO}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return c$.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:QO}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:QO}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!kn(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 mn.zJ({result:{case:"stillRunning",value:new mn.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 mn.zJ({result:{case:"complete",value:new mn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new mn.zJ({result:{case:"error",value:new mn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new mn.zJ({result:{case:"stillRunning",value:new mn.L5({agentId:r})}}):new mn.zJ({result:{case:"notFound",value:new mn.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 mn.zJ({result:{case:"stillRunning",value:new mn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new mn.zJ({result:{case:"complete",value:new mn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new mn.zJ({result:{case:"error",value:new mn.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 eF=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),tF=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),rF=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),nF=r("./src/agent/analytics.ts"),oF=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const sF={[Ag.w3.UNSPECIFIED]:"unspecified",[Ag.w3.LEFT]:"left",[Ag.w3.RIGHT]:"right",[Ag.w3.MIDDLE]:"middle",[Ag.w3.BACK]:"back",[Ag.w3.FORWARD]:"forward"},iF={[Ag.Dh.UNSPECIFIED]:"unspecified",[Ag.Dh.UP]:"up",[Ag.Dh.DOWN]:"down",[Ag.Dh.LEFT]:"left",[Ag.Dh.RIGHT]:"right"},aF={[Ag.EB.UNSPECIFIED]:"unspecified",[Ag.EB.TAP]:"tap",[Ag.EB.DOWN]:"down",[Ag.EB.UP]:"up"};function cF(e){return sF[e]??"unspecified"}function lF(e){return void 0===e?void 0:{x:e.x,y:e.y}}function uF({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:lF(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 dF(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 hF("tool-call-started",e.message.value);case"partialToolCall":return hF("partial-tool-call",e.message.value);case"toolCallCompleted":return hF("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"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=dF(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"modelCallCompleted":case void 0:return null;default:return e.message,null}}function hF(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:yF(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:vF(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:bF(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:SF(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:_F(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:CF(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:EF(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:PF(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:IF(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:TF(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:AF(t.mode)},...r?{result:$F(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:RF(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:MF(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:OF(e.status)})))},...r?{result:DF(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:lF(e.value.coordinate)};case"click":return{type:"click",coordinate:lF(e.value.coordinate),button:cF(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:cF(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:cF(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:lF(e.value.coordinate),direction:iF[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:aF[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?uF(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:pF(t),...r?{result:gF(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"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":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 pF(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:fF(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:mF(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function fF(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function mF(e){switch(e){case gn.FL.AGENT:return"agent";case gn.FL.PLAN:return"plan";default:return"unspecified"}}function gF(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:wF(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function wF(e){switch(e){case gn.qL.AGENT_REQUEST:return"agentRequest";case gn.qL.USER_REQUEST:return"userRequest";case gn.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function yF(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 vF(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 bF(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 SF(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]=kF(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:kF(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function kF(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 _F(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 CF(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 EF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:xF(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function xF(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(xF)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function PF(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:FF(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 IF(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 RF(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 TF(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 AF(e){switch(e){case MR.$u.START_RECORDING:return"START_RECORDING";case MR.$u.SAVE_RECORDING:return"SAVE_RECORDING";case MR.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function $F(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 MF(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 DF(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:OF(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function OF(e){switch(e){case oF.Vj.UNSPECIFIED:case oF.Vj.PENDING:return"pending";case oF.Vj.IN_PROGRESS:return"inProgress";case oF.Vj.COMPLETED:return"completed";case oF.Vj.CANCELLED:return"cancelled";default:return"pending"}}function FF(e){switch(e){case UI.h_.UNSPECIFIED:case UI.h_.ERROR:return"error";case UI.h_.WARNING:return"warning";case UI.h_.INFORMATION:return"information";case UI.h_.HINT:return"hint";default:return"error"}}const NF={type:"object",properties:{},additionalProperties:!0};function jF(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function LF(e){return"text"===e.type?new er._Z({content:{case:"text",value:new er.zN({text:e.text})}}):new er._Z({content:{case:"image",value:new er.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function UF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var BF=r("./src/agent/errors.ts");const WF="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 HF(e){return{async execute(){throw new Error(e)}}}function qF(e){var t;e.register(Ir,HF(WF)),e.register(Rr,(t=WF,{async*execute(){throw new Error(t)}})),e.register(le,HF(WF)),e.register(Lr,HF(WF)),e.register(ue,HF(WF)),e.register(_r,HF(WF)),e.register(we,HF("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(be,HF("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var zF=r("./src/agent/filesystem/executors.ts"),GF=r("./src/agent/filesystem/compose.ts"),VF=r("./src/agent/filesystem/trees.ts"),KF=r("./src/agent/filesystem/walk.ts");const JF="/tmp",ZF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function XF(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,KF.eI)(e.hostProjectDir),r=(0,KF.eI)(e.writePath);return"/"!==t&&(0,KF.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,KF.eI)(e.writePath):(0,KF.eI)(`${JF}/${r}`);if(!(0,KF.hJ)({path:n,prefix:JF}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(JF,pl);return s.default.posix.dirname(n)===i&&ZF.test(o)?s.default.posix.join(JF,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 QF{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,KF.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([YF(e,s.posix.join(t,".cursor/rules")),eN(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 YF(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 tN(e,t),n=void 0===r?null:b(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 eN(e,t){const r=await tN(e,t);if(void 0!==r)return fg({path:t,body:y({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function tN(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const rN={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},nN={async exec(){throw new Error("git is not available in a FileSystem session")}},oN={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function sN(e){return{cursorRulesService:!0===e.includeProjectRules?new QF(e.fs,e.workspace):rN,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:nN,ignoreService:oN,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function iN(e,t){const r=t.workspace??"/",n=(0,zF.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:XF({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...sN({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:JF,excludeHooks:!0,excludeProjectMcp:!0}}var aN=r("./src/agent/executor-common.ts"),cN=r("./src/agent/native/vendored-tree-sitter.ts"),lN=r("./src/agent/platform-package-locator.ts"),uN=r("./src/agent/sdk-config.ts"),dN=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hN=r("./src/agent/utils/logger.ts");const pN={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fN=new Map;async function mN(e){try{const t=await async function(e){const t=await(0,aN.dC)(e,aN.EV);if(!t)return;const r=aN.EV.endsWith("/")?aN.EV.slice(0,-1):aN.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,aN.tF)(),"x-ghost-mode":(0,aN.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hN.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gN(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pN;const r=new dN.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gN(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,aN.tF)()}}}catch(e){hN.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,aN.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 hN.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pN}}function gN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wN(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yN=r("./src/agent/tools-option.ts");class vN{async requestApproval(){return{approved:!0}}}function bN(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof bA))throw new BF.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Gt),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Nt}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new er.iz({result:{case:"error",value:new er.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:UF(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?sr.Struct.fromJson(t.structuredContent):void 0;return new er.iz({result:{case:"success",value:new er.QW({content:t.content.map(LF),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 er.iz({result:{case:"error",value:new er.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vN;e.resources.base.register(Gt,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Nt}(t)){const o=await lE(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 SN=new Set(["127.0.0.1","localhost","[::1]"]);function kN(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _N(){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 CN={warn(){},error(){}},EN={log(){}};class xN{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PN(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 PN(e){switch(e.type){case $w.Shell:return"this shell command";case $w.Mcp:return"this MCP tool call";case $w.Write:return"this file edit";case $w.Delete:return"this file deletion";default:return"this operation"}}function IN(e){return void 0!==e&&"insecure_none"!==e.type}async function RN(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,ye.q6)().with(C._O,EN),c=DO(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&&SN.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}`);jc=e}((0,uN.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(aN.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let d=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,aN.ly)(r.apiKey),(0,aN.mU)(r.apiKey)]),d=performance.now()-e}const h=r.workingDirectory||process.cwd();(0,cN.configureVendoredTreeSitterWorkspaceDir)(h);for(const e of r.dirs??[])(0,cN.configureVendoredTreeSitterWorkspaceDir)(e);const p=(0,Zs.Rv)((0,o.homedir)(),h),f={hostProjectDir:p,settings:{includeProjectRules:OO(c,"project"),subagentsService:new GO(r.customSubagents??[])}};let m;const g="win32"===process.platform?"rg.exe":"rg",w=process.env.CURSOR_RIPGREP_PATH;m=w&&(0,s.isAbsolute)(w)?w:(0,lN.hQ)({binaryName:g,excludedWorkspaceDir:h}),m||(m=(0,ri.xS)()),m&&(0,ri.J)(m);let y,v,b={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{y=(0,aN.KU)(r.apiKey,r.teamId);const e=(0,Dn.createClient)(oO.I,y),t=function(e){let t=fN.get(e);return t||(t=mN(e),fN.set(e,t),t.then((r=>{r===pN&&fN.get(e)===t&&fN.delete(e)}),(()=>{fN.get(e)===t&&fN.delete(e)}))),t}(r.apiKey);v=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};b=new n$(new e$(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===l?{}:{hostMcpBridgeUrls:l},isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hN.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const S=performance.now(),k=r.apiKey?await(0,ri.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,_=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=IN(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,ri.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,lN.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,ri.St)({sandboxBinaryPath:r})}(t),!(0,ri.K3)(void 0,{ctx:e.initializationCtx}))throw new BF.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,ri.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:h,perUserSandboxPolicy:k,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,E=performance.now()-S,x=_?.defaultSandboxPolicy,P=_?.defaultSandboxPolicySources,I=IN(x),R=performance.now(),T=(()=>{const e=[],t=new Set;for(const n of[h,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),A={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},$=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=DO(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,ri.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new ry,h=new ll(d,a,n),p=new HO,f=new qO,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new WO(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=OO(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=_||OO(i,"project")||OO(i,"user")||b,x=OO(i,"project")||OO(i,"user")||OO(i,"mdm"),P=OO(i,"team"),I=P&&void 0!==e.dashboardTransport,R=OO(i,"project")||OO(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:OO(i,"project"),includeUserMcp:OO(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>UO({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:A$({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:fO({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:nO({includeProjectHooks:OO(i,"project"),includeUserHooks:OO(i,"user"),includeEnterpriseHooks:OO(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:iO({includeProjectExtensibility:OO(i,"project"),includeUserExtensibility:OO(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:CO({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=>new zO(new oT(e)),createSessionMcpLease:(t,r)=>A$({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{const r=w??new BO;return{pendingDecisionStore:r,fileChangeTracker:new Uw(t),permissionsService:new dP(h,r,g,a,t,e.respectAdminControls??!1)}}}),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 tO(new KD(e.resources,n.hookExecutor,(()=>function(e,t){const r=XD(t,QD,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:XD(t,QD,"generationId","generation_id")??r,model:XD(t,QD,"model")??"unknown",...ze({modelId:XD(t,QD,"modelId","model_id"),modelParams:XD(t,eO,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new GO(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Rg([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return c$.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:h,...void 0!==T?{dirs:T}:{},projectDir:p,teamSettingsService:b,initializationCtx:a,dashboardTransport:y,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:x,defaultSandboxPolicySources:P,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new xN:void 0,getNetworkAllowlistInfo:I?()=>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,ri.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,ri.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(b,(0,o.homedir)(),h):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_N,getPowershellUtf8Options:async()=>{if(void 0===v)return A;try{const e=await v;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return A}},isLinkSharedPaymentTokenLogRedactionEnabled:wN(v),respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),M=performance.now()-R;let D,O;return(0,nF.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(d),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(M),load_sandbox_policy_ms:Math.round(E),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,c$.ni)(CN,(async()=>{const s=(0,i.VI)((0,ye.q6)().withName("sdk.run").with(C._O,EN)),[a,c]=s.ctx.withCancel(),l=t.sessionId??(0,Mn.C)(),u=t.mcpServersOverride,d=void 0===(p=t.customTools)?[]:Object.entries(p).map((([e,t])=>({clientKey:Nt,providerIdentifier:Nt,toolName:e,name:`${Nt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??NF,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:jF(t.annotations)},source:"internal"})));var p;let m;const g={...f,workspace:t.fileSystemWorkspace},w=void 0===t.fileSystem?void 0:(y=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),v=y,(0,GF.VL)({"/":v,[JF]:(0,VF.Om)()}));var y,v;m=await $.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:d,...void 0===w?kN(t.sessionResources):iN(w,g)});const b=new Map;try{const s=m.resources.wrapped;bN(m,t.customTools),void 0!==w&&qF(m.resources.base);const i=t.blobStore??new Tn.ve;let p=t.initialState??new qr.Y9z({});const f=void 0!==t.model?new tF.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new tF.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,v=Array.isArray(y)?y.map((e=>{const t=(0,Mn.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,aN.v8)(r);return new rF.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=v.length>0?new rF.xv({selectedImages:v}):void 0,C=function(e){switch(e){case"agent":return qr.xyI.AGENT;case"plan":return qr.xyI.PLAN;default:return}}(t.mode),E=!0===e.summarize?new qr.QFf({action:{case:"summarizeAction",value:new qr.Scs}}):new qr.QFf({action:{case:"userMessageAction",value:new qr.Vtf({userMessage:new qr.RGk({text:e.text,selectedContext:_,...void 0!==C?{mode:C}:{}})})}}),x={sendUpdate:async(e,t)=>{const r=dF(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return Yr(e.id);case"webFetchRequestQuery":return tn(e.id);case"switchModeRequestQuery":return on(e.id);case"askQuestionInteractionQuery":return nn(e.id,new $o.tz({result:{case:"rejected",value:new $o.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return an(e.id,new Gr.bK({result:{case:"success",value:new Gr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return cn(e.id,new Oo.r$({result:{case:"success",value:new Oo.JH}}));case"replaceEnvArgs":return ln(e.id,new Do.dV({result:{case:"failure",value:new Do.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return un(e.id,new Mo.HL({result:{case:"error",value:new Mo.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return dn(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return hn(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return pn(e.id,e.query.value.args?.description);case void 0:throw new BF.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new BF.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(D!==t.apiKey||!O){await Promise.all([(0,aN.ly)(t.apiKey),(0,aN.mU)(t.apiKey)]);const e=(0,aN.KU)(t.apiKey,r.teamId),n=Ks((0,Dn.createClient)(eF.N,e),{injectTraceHeaders:!0});O=new Us(n),D=t.apiKey}const P=(0,aN.Vh)(O,(()=>{const e=(0,aN.KU)(t.apiKey,r.teamId),n=Ks((0,Dn.createClient)(eF.N,e),{injectTraceHeaders:!0}),o=new Us(n);return O=o,D=t.apiKey,o})),I=function(e){return{...void 0!==e.allowedTools?{[yN.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yN.VJ]:e.disallowedTools.join(",")}:{}}}(t),R=new YO({agentClient:P,getResources:async({agentId:e})=>{let r=b.get(e);return r||(r=await $.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:d,...void 0===w?kN(t.subagentInherit):iN(w,g)}),bN(r,t.customTools),void 0!==w&&qF(r.resources.base),r.resources.base.register(yn,T),r.resources.base.register(vn,A),r.resources.base.register(bn,M),b.set(e,r)),r.resources.wrapped},mcpTools:d,workspacePath:h,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==w)&&Object.keys(I).length>0?{headers:I}:{},onSessionReleased:e=>{const t=b.get(e);t&&(t.dispose(),b.delete(e))}}),T=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 mn.vS({result:{case:"error",value:new mn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new mn.vS({result:{case:"error",value:new mn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new mn.vS({result:{case:"success",value:new mn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new mn.vS({result:{case:"success",value:new mn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof Qr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof wn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new mn.vS({result:{case:"error",value:new mn.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}}}(R),A=(k=R,{execute:(e,t)=>k.awaitBackgroundRunBounded(e,t)}),M=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(R);m.resources.base.register(yn,T),m.resources.base.register(vn,A),m.resources.base.register(bn,M);const F=$.services.hooksRuntime,N="object"==typeof(S=F)&&null!==S&&"workspacePath"in S&&"string"==typeof S.workspacePath&&"createSessionRuntime"in S&&"function"==typeof S.createSessionRuntime?F:void 0,j=void 0!==N&&void 0===w&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ke.sessionStart)||t.hooksConfigLease.hasHookForStep(ke.sessionEnd)||t.hooksConfigLease.hasHookForStep(ke.stop)||t.hooksConfigLease.hasHookForStep(ke.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(ke.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),is_background_agent:!1},r=await n.executeHookForStep(ke.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){c$.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(ke.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?ze(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(ke.sessionEnd,r)}catch(e){c$.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(ke.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(ke.beforeSubmitPrompt,t)}catch(e){c$.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(ke.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(ke.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(ke.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(ke.stop,t)}catch(e){c$.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(ke.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...ze(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(ke.stop,t)}catch(e){c$.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:N,sessionState:m.state,metadata:m.metadata}):void 0,L=new ZO({workspacePath:h,conversationId:l,blobStore:i}),U=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new a$;let a;const c=new Map,l=(e,t)=>{const r=c.get(e);void 0!==r&&(c.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let u;const d=[],h=e=>{for(const t of d.splice(0))t.resolve(e)},p=()=>{if(0===d.length)return;const e=d.map((e=>e.text)).join("\n\n");return h("complete_delivered"),f$(e)},f=r.interactionListener,m={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:c.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):(c.delete(t),s.resolve(e))}}await f.sendUpdate(e,t)},query:(e,t)=>f.query(e,t),...void 0!==f.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>f.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==f.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>f.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let g=r.initialState;const w={async handleCheckpoint(e,t){g=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>g};let y="completed";const v=Date.now(),b=u$(function(e,t){if((0,Tn.TU)(t))return t;const r=d$.get(e);if(void 0!==r)return r;const n=(0,Tn.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return d$.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=p$(r,0,h$(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw y="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==y)throw e;c$.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,d=0;for(;s;){const e=p$(r,d,h$(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){c$.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,Mn.C)();try{await r.agentClient.run(o,g,s,void 0,m,r.resources,r.blobStore,i,w,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:b,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw y=m$(t)?"aborted":"error",g$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...c.keys()])l(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw y="error",e}const f="string"==typeof t?t.trim():"";let v;if(f.length>0)v=f$(f);else{const t=new AbortController;u=t;try{v=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw y=o.signal.aborted||m$(r)?"aborted":"error",g$("aborted"===y?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{u=void 0}void 0===v?v=p():h("revert_to_followup")}void 0!==v?(d+=1,i.resetStream(),s=v):s=void 0}})().finally((async()=>{h("revert_to_followup");const e=Date.now()-v;try{await(n?.onSessionEnd?.(y,e))}catch(e){c$.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){c$.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=u;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{d.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,Mn.C)(),n=new Promise((e=>{const t=setTimeout((()=>{l(r,"revert_to_followup")}),15e3);t.unref?.(),c.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new qr.QFf({action:{case:"injectContextAction",value:new qr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new qr.oW$({userMessage:new qr.RGk({messageId:(0,Mn.C)(),text:e})})}})}})),await n}catch(e){return l(r,"revert_to_followup"),c$.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,E,{agentClient:P,interactionListener:x,resources:s,blobStore:i,initialState:p,conversationId:l,mcpTools:d,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:f,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(I).length>0?{headers:I}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:j,async nextAction(e,t){const r=await R.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new qr.QFf({action:{case:"backgroundTaskCompletionAction",value:new qr.Kwc({completions:e.map((e=>new qr.KFq({taskId:e.agentId,kind:qr.aZc.SUBAGENT,status:"success"===e.status?qr.uHL.SUCCESS:"aborted"===e.status?qr.uHL.ABORTED:qr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){p=e,L.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),B=U.done.finally((async()=>{try{await R.awaitBackgroundWorkers()}finally{await L.waitForPendingWrites().catch((()=>{}));for(const e of b.values())try{await e.dispose()}catch(e){hN.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}b.clear(),await m.dispose()}})).catch((e=>{throw e}));return{abort(){U.abort(),c()},done:B,steer:e=>U.steer(e)}}catch(e){for(const e of b.values())try{await e.dispose()}catch{}throw b.clear(),await m.dispose(),e}var S,k})),async reload(){await $.reload()},async dispose(){await $.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)},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>q,ME:()=>L,_N:()=>H,b6:()=>j,bi:()=>P,mD:()=>A,vc:()=>O});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=F(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<=I&&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}}(F(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=F(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=F(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=F(e);return v.test(t)||function(e){const t=F(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=F(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=F(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(R.has(e))return R.get(e);R.size>=I&&R.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=`${F(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 R.set(e,t),t}const I=2048,R=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("*")&&F(s)===F(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=N(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!F(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(F(r.hostname)!==F(o))return}return r}}function O(e,t){if(A(e,t))return!0;let r;return T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=N(t),T.set(t,r)),!!r&&h(r.hostname,e)}function F(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function N(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 j(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function L(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=j(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(F(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 U(e){const t=e?.trim();return t&&t.length>0?t:void 0}function B(e){return U(e)?.toLowerCase()}function W(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function H({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=U(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=>function(e,t){const r=B(e.builtinServer),n=B(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=U(e.command),s=U(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&&O(s,t.url);return i&&a}(e,t)))}(c,t),d=W(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||W(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!==U(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!==U(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:()=>Yr,Ls:()=>d,SandboxUnsupportedError:()=>Ft,J:()=>_,St:()=>jt,Fn:()=>Qr,ue:()=>o,r5:()=>he,oG:()=>Rr,Ko:()=>P,CG:()=>je,W1:()=>V,G6:()=>Xr,_B:()=>Ie,OK:()=>xe,$b:()=>Pe,K3:()=>Bt,tv:()=>Oe,wG:()=>qe,fZ:()=>Ge,s9:()=>Ue,XX:()=>He,T6:()=>Te,Po:()=>Re,$6:()=>Me,l7:()=>Fe,xS:()=>k,resolveSandboxPolicyForWorkspace:()=>Je,spawnInSandbox:()=>Lt,Xw:()=>x});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function i(e){const t={...e};for(const e of s)delete t[e];return t}const a=[["core.quotePath","false"]];function c(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=y(e,r);if(p.existsSync(n))return v(n,t,r)}for(const o of n){const n=y(`${e}${o}`,r);if(p.existsSync(n))return v(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:h.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:h.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 b;const S=["/usr/local/bin","/usr/bin","/bin"];function k(){const e=v("rg",[]).cmd;return"rg"!==e?e:void 0}function _(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");b=e}function C(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 E(e,t){const r=(0,h.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=C(e);return void 0!==t?e[t]??"":""}(e).split(h.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=S),function(e,t){const r=C(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(h.delimiter))}function x(e){return b&&(0,h.isAbsolute)(b)?{...E(e,b),CURSOR_RIPGREP_PATH:b}:e}function P(){if(!b)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return b}const I="win32"===process.platform;function R(e){return!I&&!!e?.SUDO_ASKPASS}function T(e){return R(e)?"alias sudo='sudo -A'; ":""}function A(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 M=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function D(e){M.some((t=>$(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function O(e){$(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const F="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",N=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],j=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${N.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${F}";; esac; `,L=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${N.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${F}" } else { $env:MAVEN_OPTS = '${F}' }\n}`;var U=r("node:crypto?8af2"),B=r("node:os"),W=r("../utils/dist/workspace-paths.js"),H=r("../utils/dist/test-resets.js");let q;function z(e,t){const r=(0,p.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function G(e){try{(0,p.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function V(e){return K(e,{create:!1})}function K(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,h.join)((0,B.tmpdir)(),`cursor-sandbox-${(0,W.r_)((0,h.resolve)(e))}`);try{for(const e of[n,(0,h.join)(n,"tmp")])if(t&&G(e),!z(e,r))return;return n}catch{return}}(0,H.J)((function(){q=void 0}));const J='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function Z(e=(0,h.join)((0,B.tmpdir)(),"cursor-sandbox-cache",function(){return q||(q=(0,U.randomBytes)(16).toString("hex")),q}())){return{NPM_CONFIG_CACHE:(0,h.join)(e,"npm"),PNPM_STORE_PATH:(0,h.join)(e,"pnpm-store"),GOCACHE:(0,h.join)(e,"go-build"),GOMODCACHE:(0,h.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,h.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,h.join)(e,"pip"),UV_CACHE_DIR:(0,h.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,h.join)(e,"bun"),YARN_CACHE_FOLDER:(0,h.join)(e,"yarn"),npm_config_devdir:(0,h.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,h.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,h.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,h.join)(e,"turbo"),GRADLE_USER_HOME:(0,h.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,h.join)(e,"conda"),POETRY_CACHE_DIR:(0,h.join)(e,"poetry"),GEM_SPEC_CACHE:(0,h.join)(e,"gem-specs"),BUNDLE_PATH:(0,h.join)(e,"bundle"),COMPOSER_HOME:(0,h.join)(e,"composer"),HOMEBREW_CACHE:(0,h.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,h.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,h.join)(e,"nx"),NUGET_PACKAGES:(0,h.join)(e,"nuget"),CCACHE_DIR:(0,h.join)(e,"ccache"),CP_HOME_DIR:(0,h.join)(e,"cocoapods")}}var X=r("node:fs/promises"),Q=r("node:child_process"),Y=r("node:string_decoder"),ee=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),te=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class re extends Error{constructor(e,t,r,n,o,s){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=o,this.stderr=s,this.command=r,this.args=n,"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,re)}}function ne(e,t,r){r=r??{};let n=new ee.Observable((n=>{const{encoding:o,timeout:s,...i}=r,{cmd:a,args:c}=v(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const u=(0,Q.spawn)(a,c,i);r.processInfo&&void 0!==u.pid&&(r.processInfo.pid=u.pid);let d=null;s&&s>0&&(d=setTimeout((()=>{u.killed||u.kill();const e=new re(`Process timed out after ${s}ms`,-1,a,c);n.error(e)}),s));const h={stdout:new Y.StringDecoder(o||"utf8"),stderr:new Y.StringDecoder(o||"utf8")},p=t=>o=>{if(o.length<1)return;let s;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(o);try{s="string"==typeof o?o:h[t].write(o)}catch{s=`<< Lost chunk of process output for ${e} - length was ${o.length}>>`}s.length>0&&n.next({source:t,text:s})},f=e=>{const t=h[e].end();t.length>0&&n.next({source:e,text:t})},m=new ee.Subscription;if(l)if(u.stdin){const e=u.stdin;m.add(l.subscribe({next:t=>e.write(t),error:n.error.bind(n),complete:()=>e.end()}))}else n.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let g=null,w=null,y=!1;if(u.stdout){const e=new ee.AsyncSubject;w=e,u.stdout.on("data",p("stdout")),u.stdout.on("close",(()=>{f("stdout"),e.next(!0),e.complete()}))}else w=(0,ee.of)(!0);if(u.stderr){const e=new ee.AsyncSubject;g=e,u.stderr.on("data",p("stderr")),u.stderr.on("close",(()=>{f("stderr"),e.next(!0),e.complete()}))}else g=(0,ee.of)(!0);return u.on("error",(e=>{y=!0,d&&clearTimeout(d),n.error(e)})),u.on("close",(e=>{y=!0,d&&clearTimeout(d);const t=(0,ee.merge)(w,g).pipe((0,te.TS)((e=>!0),!0));0===e?t.subscribe((()=>n.complete())):t.subscribe((()=>{const t=new re(`Process failed with exit code: ${e}`,e,a,c);n.error(t)}))})),m.add(new ee.Subscription((()=>{y||(d&&clearTimeout(d),u.kill())}))),m}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;n=n.pipe((0,te.L5)({count:e,delay:(e,r)=>{if(e instanceof re&&0!==e.exitCode)return(0,ee.timer)(t);throw e}}))}return r.split?n:n.pipe((0,te.Tj)((e=>e?.text)))}function oe(e,t,r){return r?.split?(n=ne(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",o="";n.subscribe({next:e=>{"stdout"===e.source?r+=e.text:o+=e.text},error:e=>{if(e instanceof re){const n=new re(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,o);t(n)}else{const n=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(n)}},complete:()=>e([r,o])})}))):function(e){return new Promise(((t,r)=>{let n="";e.subscribe({next:e=>{n+=e},error:e=>{if(e instanceof re){const t=new re(`${n}\n${e.message}`,e.exitCode,e.command,e.args,n,e.stderr);r(t)}else{const t=new Error(`${n}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(n)})}))}(ne(e,t,{...r??{},split:!1}));var n}var se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const ie=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ae=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],ce=(e,t)=>t.flatMap((t=>ae.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),le={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},ue=e=>[...ie,...le[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),de=[{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"},...ue("linux"),...ce("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"},...ue("darwin"),...ce("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 he(e=process.platform,t=B.default.homedir(),r={}){const n=[];for(const o of de){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,h.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,p.lstatSync)(s).isFile();break;case"home-dir":e=(0,p.lstatSync)(s).isDirectory();break;case"bundled":e=(0,p.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const pe=[{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:"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"}];function fe(e){const t=pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function me(e){const t=pe.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}pe.filter((e=>"git"===e.type)).map((e=>e.pattern)),pe.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const ge=[];let we=null,ye=null;let ve=null;const be=new Map;const Se="win32"===process.platform||"darwin"===process.platform;function ke(e){if(!e.endsWith(h.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function _e(e){return e.endsWith(h.sep)?e:e+h.sep}function Ce(e,t){const r=ke(t);if(Se){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(_e(n))}return e===r||e.startsWith(_e(r))}function Ee(e,t){const r=ke(e);return Se?(0,h.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,h.relative)(r,t).replace(/\\/g,"/")}async function xe(e,t){if(Ce(e,t)){const r=Ee(t,e);if((null===we&&(we=se({ignoreCase:!0}),we.add(pe.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),we).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=be.get(e);if(t)return t;const r=await(0,X.stat)((0,h.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return be.set(e,t),t}const n=await async function(e){try{const t=await oe("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,h.dirname)((0,h.resolve)(e,t.trim()))}catch{return null}}(e),o={isWorktree:!0,gitDirParent:n??e};return be.set(e,o),o}(t);if(Ce(e,n)){const t=Ee(n,e);if((null===ye&&(ye=se({ignoreCase:!0}),ye.add(pe.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ye).ignores(t))return!0}if(r&&Ce(e,t)&&".git"===Ee(t,e))return!0;for(const t of function(){if(null!==ve)return ve;const e=B.default.homedir(),t=[];for(const r of pe)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,h.join)(e,r.pattern))}return ve=t,t}())if(Ce(e,t))return!0;return!1}function Pe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ie(e){return void 0!==e&&"allow"===e.default}function Re(){return{version:1,default:"deny"}}function Te(){return{version:1,default:"allow"}}var Ae=r("../utils/dist/path-utils.js");function $e(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 Me(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:$e(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function De(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","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 Oe(e,t){const r=await async function(e,t){try{const r=await(0,X.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==De(n))return{success:!1,error:`Invalid sandbox policy: ${De(n)??""}`};let o=Me(n);return t&&(o=Fe(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 Fe(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ae.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ae.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ae.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var Ne=r("../utils/dist/safe-spawn-cwd.js");function je(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Le(...e){return e.some((e=>!0===e))}function Ue(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ze(e));return[...t]}const Be=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]function(...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=ze(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ze);let r=new Set(t[0].map(ze));for(let e=1;en.has(e))))}return[...r]}(...e);function He(...e){return Be.merge(...e)}function qe(...e){return We(...e)}function ze(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Ge(...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 Ve(...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)){const e=r[t];if(e){const o=new Set(e);for(const e of n)o.has(e)&&o.delete(e),o.add(e);r[t]=[...o]}else r[t]=[...n]}return 0!==Object.keys(r).length?r:void 0}function Ke(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Je(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,Ne.$f)(e))return Ze(t,{workspaceDir:e});const n=r.stat??X.stat,o=r.spawnPromise??oe,s=await n((0,h.join)(e,".git")).then((e=>e),(()=>null)),i=s?.isFile()??!1,a=null!==s;if("workspace_readwrite"===je(t)){let r=e;if(i){const n=await o("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,h.resolve)(e,t.trim())),(()=>null));if(n){r=(0,h.dirname)(n);const o=t.perRepo,s=o?.ignoreMapping;t={...t,perRepo:{...o,type:"workspace_readwrite",additionalReadwritePaths:[...o?.additionalReadwritePaths??[],n],ignoreMapping:s,writeProtectionMapping:Ve(o?.writeProtectionMapping,me(e))}}}}if(a)return Ze(t,{workspaceDir:e,gitDirParent:r})}return Ze(t,{workspaceDir:e})}function Ze(e,t){return function(e,t){const r=function(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}(e);if(void 0===r)return tt({},t);switch(r){case"workspace_readwrite":return tt(Qe(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ye(e,t),o={policy:et({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,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Qe(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:et({type:"insecure_none",allowlistEscalated:Le(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:Ke(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:Le(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:Ke(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Qe(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Xe(e,t){return e?.type===t}function Qe(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Xe(r,t)?r:void 0,perRepo:Xe(n,t)?n:void 0,teamAdmin:Xe(o,t)?o:void 0}}function Ye(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!==ge.length)return{version:1,deny:[...ge]}}(),r=B.default.homedir(),n=[];for(const e of pe)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,h.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:fe(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")},p=Le(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 f=Le(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=Ke(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=Ke(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?Ue(s.additionalReadPaths):Ue(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=Ue(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=Ge(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=Ke(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=Le(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=Ke(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=Ve(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=function(e){const t=pe.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??i);return{disableTmpWrite:p||void 0,networkPolicyStrict:f,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:Ve(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function et(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 tt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ye(e,t),a=Ue(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:et({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,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var rt=r("../utils/dist/workload-spawn.js"),nt=r("../context/dist/logger.js"),ot=r("../context/dist/core.js");const st=Q.execFile,it=new WeakMap;function at(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}let ct=0;function lt(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?h.resolve(e):h.resolve(h.join(B.homedir(),".cursor","sandbox-policies"))}();p.mkdirSync(e,{recursive:!0,mode:448});try{p.chmodSync(e,448)}catch{}const t=Date.now();return t-ct>=9e5&&(ct=t,function(e){let t;try{t=p.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=h.join(e,n);try{const e=p.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&p.unlinkSync(t)}catch{}}}(e)),e}function ut(e){const t=lt(),r=U.randomBytes(8).toString("hex"),n=h.join(t,`sandbox-policy-${r}`);return p.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const dt="darwin"===process.platform,ht="linux"===process.platform,pt=(0,nt.h)("shell-exec:sandbox");function ft(e){const t=lt();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let mt,gt=!0,wt=!1;function yt(){return mt}function vt(e){"linux"===process.platform&&Object.assign(e,x(e))}let bt=null,St=null,kt=null,_t=null,Ct=!1,Et=null;function xt(e){return{...e,additionalReadonlyPaths:ft(e.additionalReadonlyPaths)}}function Pt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return Mt(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,p.existsSync)(r)&&(0,p.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=function(e,t=e=>p.existsSync(e)){if((0,Ne.$f)(e))return!0;let r=h.resolve(e);for(;;){try{if(t(h.join(r,".git")))return!0}catch{}const e=h.dirname(r);if(e===r)return!1;r=e}}(r),s=!ht||o?t??{}:{},i={...n};for(const[e,t]of Object.entries(s))i[e]?i[e]=[...i[e],...t]:i[e]=t;if(0!==Object.keys(i).length)return Mt(i)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=gt;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=P()}catch{}for(const o of he(e,B.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=B.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=h.join(B.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=h.basename(e);if((o.includes("*")||o.includes("?"))&&(e=h.dirname(e)),!e||"."===e)continue;const s=h.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Pe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function It(e){const t={sandbox:e};return ht&&function(){const e=wt;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Rt(e){if(null!==bt)return bt;try{const t=yt();return pt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(bt=p.existsSync(t),bt?pt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(bt)}`):(St=new Error(`Sandbox binary not found at ${t}`),pt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),bt):(St=new Error("Sandbox binary path was not configured"),bt=!1,pt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return St=t instanceof Error?t:new Error(String(t)),bt=!1,pt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Tt(e){if(null!==_t)return _t;const t=e??(0,ot.q6)();if(pt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Rt(t)){const e=St?.message||"Binary check failed";return kt=e,pt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),_t=!1,_t}if("win32"===process.platform)return kt="Windows sandbox helper only provides network proxy, not filesystem isolation",pt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),_t=!1,_t;if("darwin"===process.platform)return kt=null,pt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),_t=!0,_t;const{binaryPath:r,args:n,env:o}=function(e,t){const r=It(Pt(xt({type:"workspace_readwrite"}),t)),n=String(yt());pt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),pt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return vt(o),{binaryPath:n,args:["--policy",ut(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,rt.D9)(Q.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:At,env:o,shell:!1});const s=Date.now()-e;return kt=null,pt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),_t=!0,_t}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return pt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),pt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&pt.error(e,`[sandboxPreflight] Stderr: ${o}`),kt=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"}`,_t=!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,H.J)((function(){_t=null,Ct=!1,Et=null,kt=null,bt=null,St=null}));const At=15e3;function $t(e,t=[],r={},n){const s=(0,ot.q6)();if(r.env=o(r.env),!Rt(s))throw new Error(`Sandbox binary not available: ${St?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,rt.D9)(Q.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let c=e,l=t;r.shell&&("win32"===process.platform?(c="string"==typeof r.shell?r.shell:"cmd.exe",l=["/c",`${e} ${t.join(" ")}`]):(c="string"==typeof r.shell?r.shell:"/bin/sh",l=["-c",`${e} ${t.join(" ")}`]));const u=Pt(xt(n),a),d=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return K(e.cwd,{create:!0})}(u);d&&(u.additionalReadwritePaths=[...u.additionalReadwritePaths??[],d]);const p=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Pe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),f=It(u);void 0!==p&&(f.networkPolicy=p),!1===n.networkPolicyStrict&&(f.networkPolicyStrict=!1);const m=["--policy",ut(JSON.stringify(f)),"--",c,...l],g=o(process.env),w={..."linux"===process.platform?i(g):g,..."linux"===process.platform&&r.env?i(r.env):r.env,CURSOR_SANDBOX:"native"};if(vt(w),d){const e=function(e,t,r){const n=function(e){const t=(0,h.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,h.join)(t,"sh-")}}(e);if(r){const r=Z();for(const[o,s]of Object.entries(Z(e)))t[o]===r[o]&&(n[o]=s)}return n}(d,w,n.enableSharedBuildCache);Object.assign(w,e),w.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),w.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const y={cwd:r.cwd||s,env:w,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,rt.D9)(Q.spawn,String(yt()),m,y);return dt&&t.pid&&function(e,t){it.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,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function Mt(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?Dt(t):t;o[e]=r;const n=Ot(e);n!==e&&(o[n]=r)}return o}function Dt(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Ot(e,t){if((0,Ne.$f)(e))return e;try{return(t??p.realpathSync)(e)}catch{return e}}class Ft extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Nt="darwin"===process.platform;function jt(e){!function(e){P();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;mt||(mt=t),void 0!==r&&(gt=r),void 0!==n&&(wt=n)}(e)}function Lt(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...Z(),...r.env}}),"insecure_none"!==n.type){if(Tt())return $t(e,t,r,n);const o=kt;throw new Ft(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Q.spawn,spawnWorkload:rt.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function Ut(e){return Nt?async function(e){const t=it.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,rt.D9)(st,"/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:at(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:at(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 Bt(e,t){if(Nt)try{(0,p.accessSync)("/usr/bin/sandbox-exec",p.constants.X_OK)}catch{return!1}return Tt(t?.ctx)}var Wt=r("node:stream"),Ht=r("../context/dist/otel.js"),qt=r("../utils/dist/writable-iterable.js");const zt="--",Gt='builtin eval "$1" 3<&- 4>&-',Vt=50,Kt=262144;class Jt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Vt,this.maxBufferedBytes=t?.maxBufferedBytes??Kt}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 Jt(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([Xt(e.stdout,r,t),Qt(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 Xt(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 Qt(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Yt;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Yt||(Yt={}));const er={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function tr(e,t,r,n={spawn:Q.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function rr(e,t=[],r={},n,o){const s=Lt(e,t,{...r,env:x(r.env??process.env)},n);if(o){const e=function(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}({platform:process.platform,detached:!0===r.detached}),t=()=>{if(!s.pid)return;tr(s,e,"SIGTERM");const t=setTimeout((()=>{!s.killed&&s.pid&&tr(s,e,"SIGKILL")}),1e3);"process_group"!==e&&s.once("exit",(()=>{clearTimeout(t)}))};o.aborted?t():(o.addEventListener("abort",t,{once:!0}),s.once("exit",(()=>{o.removeEventListener("abort",t)})))}return s}function nr(e){const t=[];return e?.on("data",(e=>{t.push(e)})),()=>Buffer.concat(t).toString("utf8")}function or(e){e?.on("error",(()=>{}))}const sr="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 ir(e,t){return 126===e&&""===t}function ar(){return"win32"!==process.platform}function cr(e,t){const r=e.stdio.at(5);r instanceof Wt.default.Writable&&(or(r),r.end(`${t}\0`))}function lr(e,t){e&&(or(e),e.write(t),e.end())}function ur(e,t){if(!e)return;or(e);const r=new Y.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 dr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function hr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function pr(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 fr="__CURSOR_BASH_STATE_START__",mr="__CURSOR_BASH_STATE_END__";var gr=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 wr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=v("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:v("bash",[]).cmd}function yr(e){if("win32"!==process.platform)return e;const t=h.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===h.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function vr(e){const t=e.pipeStdin?Gt:`${Gt} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?sr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+J+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class br{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new br(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;h.default.resolve(t)===h.default.resolve(this.cwd)&&(this.cwd=void 0===r||h.default.resolve(r)===h.default.resolve(t)||(0,Ne.A)(r)?(0,Ne.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{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}(n,(0,Ht.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,qt.Jt)(),a=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...er,...e?.env};return c(n),"win32"===t&&(D(n),O(n)),n}(r),u=T(l),d=this.useFileStateTransport,p=!d&&!this.commandPipeUnreadable;let f,m,g;if(d){f=await(0,X.mkdtemp)(h.default.join(B.default.tmpdir(),"cursor-bash-state-")),m=h.default.join(f,"state-in"),g=h.default.join(f,"state-out"),await(0,X.writeFile)(m,this.state,"utf8"),await(0,X.writeFile)(g,"","utf8").catch((()=>{}));const e=yr(m),t=yr(g);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const w=function(e){return["-O","extglob","-c",e.script,zt,...void 0===e.command?[]:[e.command]]}({script:vr({pipeCommand:p,useFileTransport:d,sudoAliasInjection:u,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?j:""}),command:p?void 0:t}),y=wr(this.userTerminalHint);if(!y)throw new Error("Can't find Bash");const v=r?.sandboxWorkspaceRoot??a,b=(await Je(v,r?.sandboxPolicy)).policy,S="insecure_none"!==b.type?{...b,sandboxWorkspaceRoot:v}:b;let k="";const _=async()=>{if(d){if(!g)return void(k=this.state);try{k=await(0,X.readFile)(g,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),k=this.state}}},C=async()=>{if(f)try{await(0,X.rm)(f,{recursive:!0,force:!0})}catch{}};let E;(0,Ne.$Y)(a)&&(0,Ht.HF)(o.ctx,Ne.yo);try{E=rr(y,w,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:a,detached:!0},S,r?.signal)}catch(e){throw await C(),e}E.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:E.stdin??void 0,pid:E.pid})}catch(e){}}));const x=Zt({stdout:E.stdout,stderr:E.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});E.on("error",(async e=>{if((0,Ne.fK)(e,a)){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await C(),i.throw(e)}));let P=null,I=null,R=null,A=!1;const $=async e=>{if(A)return;if(A=!0,R&&(clearTimeout(R),R=null),(0,Ht.HF)(o.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await C(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,Ne.wz)({exitCode:P,stdoutBytes:x.stdoutBytes,stdoutPrefix:x.stdoutPrefix,cwd:a})&&""===k;if(t&&x.dropHeldStdout(),await x.flush(),p&&ir(P,k)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await C(),(0,Ht.HF)(o.ctx,Ne.Gq);const e=(0,Ne.iA)(a);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,Ne.Vn)(a))}if(!r?.signal?.aborted){await _();const e=`${fr}\n`,t=`${mr}\n`;if(k.startsWith(e)&&k.endsWith(t)){let t=k.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=dr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(S.captureDenies)try{const e=await Ut(E);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:P,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await C()};E.on("exit",((e,t)=>{P=e,I=t;const n=r?.closeTimeout??5e3;n>0&&(R=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),$(!1)}),n))})),E.on("close",(async()=>{await $(!0)}));const M=E.stdio[3],F=E.stdio[4],N=M instanceof Wt.default.Writable?M:null,L=F instanceof Wt.default.Readable?F:null;p&&cr(E,t),d||(lr(N,this.state),ur(L,(e=>{k+=e}))),yield*i}catch(e){n.error=e,n.hasError=!0}finally{gr(n)}}}async function Sr(e){const t={...process.env,...er,...e?.env},r="__CURSOR_STATE_MARKER__",n=["-O","extglob","-ilc",`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],o=wr(e?.userTerminalHint);if(!o)throw new Error("Can't find Bash");const s=rr(o,n,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal),i=nr(s.stdout);s.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=pr(hr(i(),r),fr,mr)??`${process.cwd()}\n`,{cwd:c,rest:l}=dr(a),u="win32"===process.platform,d="win32"===process.platform?process.cwd():c;return new br(d,l,e?.userTerminalHint,u)}var kr=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 _r{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new _r((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={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})}(n,(0,Ht.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{kr(n)}}}const Cr="\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",Er=e=>e.map((e=>`'${e}'`)).join(", "),xr=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $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 $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\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 if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.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; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\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 'either' }\n if ($__cursorFull) {\n # A full window 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 }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\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 # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\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 -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\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 # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\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}\n'@\n if (-not $__cursorHasEncodingDefault) {\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 Get-Content -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 $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\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:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # 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 @(${Er([".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 @(${Er([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${Er([".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 @(${Er([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${Er([".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 }\n }\n} catch { }\n`,Pr=String.raw` + try { + if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) { + function global:__cursorUtf8FromLatin1 { +diff --git a/dist/s2code-retry.cjs b/dist/s2code-retry.cjs +new file mode 100644 +index 0000000000000000000000000000000000000000..8a9127a367027533179bc664aa3908b83295b1a2 +--- /dev/null ++++ b/dist/s2code-retry.cjs +@@ -0,0 +1,56 @@ ++"use strict"; ++ ++const diagnostics = require("node:diagnostics_channel").channel("s2code.cursor.retry"); ++const checkpointMessage = "Cursor could not confirm that this answer was saved. Automatic replay was stopped; the next message will recover in a fresh Cursor session."; ++ ++exports.guard = function guard(input) { ++ let turnEnded = false; ++ let checkpoint = "none"; ++ const sendUpdate = input.interaction.sendUpdate; ++ input.interaction.sendUpdate = function (context, update) { ++ if (update.message?.case === "turnEnded") turnEnded = true; ++ return sendUpdate.call(this, context, update); ++ }; ++ ++ return { ++ ...input, ++ hooks: { ++ ...input.hooks, ++ runAttempt(attempt) { ++ checkpoint = "none"; ++ const handler = attempt.checkpointHandler; ++ return input.hooks.runAttempt({ ++ ...attempt, ++ checkpointHandler: { ++ ...handler, ++ async handleCheckpoint(...args) { ++ await handler.handleCheckpoint(...args); ++ checkpoint = args[2]?.resumeEligibility ?? "eligible"; ++ }, ++ }, ++ }); ++ }, ++ classify(cause, info) { ++ let decision = input.hooks.classify(cause, info); ++ const cancelled = decision.action === "throw" && decision.error.kind === "CancelledError"; ++ const blocked = turnEnded && checkpoint !== "ineligible_terminal_turn" && !cancelled; ++ if (blocked) { ++ decision = { ++ action: "throw", ++ error: input.checkpointError(cause, info.attemptRequestId, checkpointMessage), ++ }; ++ } ++ diagnostics.publish({ ++ requestId: info.attemptRequestId, ++ originalRequestId: info.originalRequestId, ++ attempt: info.attempt, ++ decision: blocked ? "blocked_after_turn_ended" : decision.action === "retry" && checkpoint === "ineligible_terminal_turn" ? "completed_from_checkpoint" : decision.action, ++ turnEnded, ++ checkpoint, ++ cause, ++ }); ++ return decision; ++ }, ++ }, ++ }; ++}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2a01f03911bbc..facc16d194e60 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -362,6 +362,7 @@ pnpmfileChecksum: sha256-HxQwAhyWNI/9fnrZxQ0MltAhBMQohaHvLg4GiiAL6JA= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e '@clerk/expo-native-components@0.4.0': 7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4 + '@cursor/sdk@1.3.1': 9539e59be889271b1778056d5961d5d9ae4764ac06ae913ad4de58cbe60c5067 '@effect/vitest@4.1.2': 299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7 '@expo/fingerprint@0.21.5': 8fba80d6bbce46c72de427fe8c7907462d262a0bfe50c6b2b7ee9c4e0c61e5e1 '@expo/metro-config@58.0.14': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760 @@ -1750,8 +1751,8 @@ importers: packages/provider-cursor: dependencies: '@cursor/sdk': - specifier: 1.2.0 - version: 1.2.0(zod@4.6.5) + specifier: 1.3.1 + version: 1.3.1(patch_hash=9539e59be889271b1778056d5961d5d9ae4764ac06ae913ad4de58cbe60c5067)(zod@4.6.5) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -3622,36 +3623,72 @@ packages: os: [darwin] hasBin: true + '@cursor/sdk-darwin-arm64@1.3.1': + resolution: {integrity: sha512-5JXgVJYeFPxXjDqnu1ha/rAmH+ATFh4abdx199x8E/RcYYM++9b55oJXO3GYv1/9/4Qa9RsE5JkHRY6FYc5vQw==} + cpu: [arm64] + os: [darwin] + hasBin: true + '@cursor/sdk-darwin-x64@1.2.0': resolution: {integrity: sha512-mJTFdX+qv9dHAm59tT7uq7ci7+BDvFoNk4gdF2zGp9SLULicY+FdFD64p1qLen1bX5Y2soZaX5mWBy7BfObjcg==} cpu: [x64] os: [darwin] hasBin: true + '@cursor/sdk-darwin-x64@1.3.1': + resolution: {integrity: sha512-yHzIRER8IpOpIH/CUigquuwqvcjCEe62xV6OiJHzRfgApdnzxCjC8JMhLZP2M08/dofyZu9xeo7yr43H6oSRTA==} + cpu: [x64] + os: [darwin] + hasBin: true + '@cursor/sdk-linux-arm64@1.2.0': resolution: {integrity: sha512-Rs+cd5snuhxMAHkpqRfEGPB1qAsfqSOYJh5SOHZTOWy2LkRVO62WHwd4x80C2emj+dosTV5WAcuF2kMKKcrDJg==} cpu: [arm64] os: [linux] hasBin: true + '@cursor/sdk-linux-arm64@1.3.1': + resolution: {integrity: sha512-8wI7DUSQtJ7Rkyj5AhNONeR0M+5bjhR0qo8GJEEmRs6isi072sNPsFXwfhlzX7bhbtsX/FCtvsTG/vpam48ObA==} + cpu: [arm64] + os: [linux] + hasBin: true + '@cursor/sdk-linux-x64@1.2.0': resolution: {integrity: sha512-ainsGAFtkWTBZrLABp82Hvfv7VB/FxmZHE42qMVotFTRDwOY2iduvhSig910bVxv+kw3S00Srmu/9CxklLwhbw==} cpu: [x64] os: [linux] hasBin: true + '@cursor/sdk-linux-x64@1.3.1': + resolution: {integrity: sha512-jIwzTr3KhMtU4aJc8x0i1RlcBKttqcVYhor9FI/h1qJQm03yTgSwhyZjsMvfBHPQ5KoYDFVdu47S1dIhwaSWZA==} + cpu: [x64] + os: [linux] + hasBin: true + '@cursor/sdk-win32-x64@1.2.0': resolution: {integrity: sha512-p3rkyta6R/nXIukd3/ifJq32otkkGoUi41T2jxnHbPHMhzE2F8OuJQGBVmORuQLMr+bIGGVZmCxertgs4WgzcQ==} cpu: [x64] os: [win32] hasBin: true + '@cursor/sdk-win32-x64@1.3.1': + resolution: {integrity: sha512-hqYllGgY27eaq+w035PebKdoc/JswcrvOSNCniqq/nicLXgWdK5zdKiAs5MyWUr73HGGL1sK0aiE7WdxbIKKVw==} + cpu: [x64] + os: [win32] + hasBin: true + '@cursor/sdk@1.2.0': resolution: {integrity: sha512-Nqm2U0zTWrYEDCv3Rdwsfa1gYZWsg+JnY+I2F8BwWSAr3FNo0TZWwyHWoWngZgriF1w02fJ4gjJWaul9zysvgQ==} engines: {node: '>=22.13'} peerDependencies: zod: ^3.25.0 || ^4.0.0 + '@cursor/sdk@1.3.1': + resolution: {integrity: sha512-Mn0gK8V+5BkOqm22J2ocU+1BrqnNH8QcK9kmA7SkRuawDOeq2ABC2BIZq9gRnF3z68x/I7J/ZU8jl6DcshCVUA==} + engines: {node: '>=22.13'} + peerDependencies: + zod: ^3.25.0 || ^4.0.0 + '@date-fns/tz@1.5.0': resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==} @@ -13694,18 +13731,33 @@ snapshots: '@cursor/sdk-darwin-arm64@1.2.0': optional: true + '@cursor/sdk-darwin-arm64@1.3.1': + optional: true + '@cursor/sdk-darwin-x64@1.2.0': optional: true + '@cursor/sdk-darwin-x64@1.3.1': + optional: true + '@cursor/sdk-linux-arm64@1.2.0': optional: true + '@cursor/sdk-linux-arm64@1.3.1': + optional: true + '@cursor/sdk-linux-x64@1.2.0': optional: true + '@cursor/sdk-linux-x64@1.3.1': + optional: true + '@cursor/sdk-win32-x64@1.2.0': optional: true + '@cursor/sdk-win32-x64@1.3.1': + optional: true + '@cursor/sdk@1.2.0(zod@4.6.5)': dependencies: '@bufbuild/protobuf': 1.10.0 @@ -13720,6 +13772,20 @@ snapshots: '@cursor/sdk-linux-x64': 1.2.0 '@cursor/sdk-win32-x64': 1.2.0 + '@cursor/sdk@1.3.1(patch_hash=9539e59be889271b1778056d5961d5d9ae4764ac06ae913ad4de58cbe60c5067)(zod@4.6.5)': + dependencies: + '@bufbuild/protobuf': 1.10.0 + '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) + '@connectrpc/connect-web': 1.7.0(@bufbuild/protobuf@1.10.0)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.0)) + '@statsig/js-client': 3.31.0 + zod: 4.6.5 + optionalDependencies: + '@cursor/sdk-darwin-arm64': 1.3.1 + '@cursor/sdk-darwin-x64': 1.3.1 + '@cursor/sdk-linux-arm64': 1.3.1 + '@cursor/sdk-linux-x64': 1.3.1 + '@cursor/sdk-win32-x64': 1.3.1 + '@date-fns/tz@1.5.0': {} '@daypicker/react@10.0.1(@types/react@19.3.0)(react@19.3.0)': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index aa1cee6bb4744..72754bc6c182d 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -265,6 +265,8 @@ patchedDependencies: app-builder-lib@26.16.1: patches/app-builder-lib@26.16.1.patch # A failed Artifacts.cached effect hangs every later caller: https://github.com/alchemy-run/alchemy/issues/2981 alchemy@2.0.0-beta.85: patches/alchemy@2.0.0-beta.85.patch + # Keep the retry-boundary guard in sync with provider-cursor's installed-SDK regression tests. + "@cursor/sdk@1.3.1": patches/@cursor__sdk@1.3.1.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning.